Returning NULL if structure initialization failed in C?
A structure is not a pointer. If you want to be able to return NULL, you're going to have to allocate the structure on the heap so you can return a pointer to it, and let the caller clean up afterwards.
That way, you can indicate failure, something like:
MyStruct *init_mystruct (void) {
MyStruct *mystruct = malloc (sizeof (*mystruct));
if (mystruct != NULL)
return NULL;
int is_ok = 1;
/* do something ... */
/* everything is OK */
if( is_ok )
return mystruct;
/* something went wrong */
free (mystruct);
return NULL;
}
int main (void) {
MyStruct *mystruct = init_mystruct();
if (mystruct == NULL) {
/* error handler */
return -1;
}
free (mystruct);
return 0;
}
NULL
can be used if a function returns a pointer. In this case, you return an object, which means that you have to return a real, existing object.
One way of doing this is to have an "ok" field in the struct that you could set in the init function, and that you could check in the caller.
Another way is to rewrite your code so that you allocate a struct dynamically and return a pointer, that way you could return NULL on failure. (Note, however, that there are other drawbacks of allocating things dynamically.)
if( mystruct == NULL )
mystruct
is not a pointer, so you cannot compare it with NULL
.
You have three options:
- Add a status field to
MyStruct
to indicate whether the struct has been initialized correctly. - Allocate the struct on the heap and return it by pointer.
- Pass the structure as a pointer argument and return a status code (thanks @Potatoswatter).