You're creating a struct and you need to destroy it later in your program. However due to some error the struct might actually not have been allocated, so you need to check if the pointer is valid (EDIT: checking for NULL
doesn't ensure the pointer is valid, see LucasHenrique's and Giorgi's comments). Basically you can do this in two ways.
Check at the 'top':
main.c:
struct my_struct* foo = create();
...
if (foo) {
destroy(foo);
}
mystruct.c:
void destroy(struct my_struct* foo) {
/* Do clean up */
}
Check at the 'bottom':
main.c:
struct my_struct* foo = create();
...
destroy(foo);
mystruct.c:
void destroy(struct my_struct* foo) {
if (foo) {
/* Do clean up */
}
}
The first one makes sure that the user is cleaning up everything correctly, but the second one gives you cleaner code inside main.c (although 'destroy' might not be the best name for that function in that case). I can't really decide which principle I should follow and I'd like to know if there are any real disadvantages to one of them?