Thank you all for your answers.
Unfortunately, I cannot use boost or other libraries in this project ... so all these suggestions are useless to me.
I looked at things like exception handling in C, like here ... http://www.halfbakery.com/idea/C_20exception_20handling_20macros
And then I looked at why C ++ doesn't finally have a Java look and stumbled upon this RAII stuff.
I'm still not sure if I will follow the path of the destructor and only make C ++ code or stick to the C exception macro (which uses the awful goto :)
Tronic suggested something like the following. With RAII, or destructors in general, should they be proof of segfault? I guess not.
The only thing I don't like is the fact that now I have to use listing (char *) in my printf statements.
#include <stdio.h> #include <stdlib.h> #include <string.h> struct CharWrapper { char* str; CharWrapper(): str() {} // Initialize NULL ~CharWrapper() { printf("%d auto-freed\n", str); free(str); } // Conversions to be usable with C functions operator char*() { return str; } operator char**() { return &str; } }; // a crappy library function that relies // on the caller to free the memory int get_a_str(char **x){ *x = (char*)malloc(80 * sizeof(char)); strcpy(*x, "Hello there!"); printf("%d allocated\n", *x); return 0; } int main(int argc, char *argv[]){ CharWrapper cw; get_a_str(cw); if(argc > 1 && strcmp(argv[1], "segfault") == 0){ // lets segfault int *bad_ptr = NULL; bad_ptr[8675309] = 8675309; } printf("the string is : '%s'\n", (char*)cw); return 0; }
source share