0

Edit: This is not a duplicate. The 'duplicate' post is about setting free'd memory to zero, this one is only about what happens with the variable! Please read the posts before flagging them or at least show in how far this is a duplicate.

Given a struct like

typedef struct simple {
    int variable;
} Simple;

I usually delete such struct by using a function

void delete_simple(Simple *simple) {
    if (simple) {
        free(simple);
    }    
}

and use it like

delete_simple(mySimple)

But I recently figured the pointer to mySimple would still remain non null, so I thought this might be a better approach:

Simple *destroy_simple(Simple *simple) {
    if (simple) {
        free(simple);
    }
    return 0;
}

and use it like

mySimple = delete_simple(mySimple)

Is this a better or worse way?

AdHominem
  • 1,204
  • 3
  • 13
  • 32
  • Both are acceptable. The advantage of setting the pointer to null is that if you try to (mis)use the pointer, you're more likely to get a crash. It isn't foolproof, though. It depends on context, too. If the pointer is in a containing structure that is about to be freed, setting to null is immaterial. If the structure will continue to be used but it is important to know whether the space is allocated, setting to null could well be crucial. – Jonathan Leffler Oct 22 '16 at 13:51
  • This is opinion based. The word better (or worse) can be used to describe behaviors that are contradicting. In other words, the reader must provide the context. – 2501 Oct 22 '16 at 13:53
  • I'm not sure, setting the pointer to NULL is at the very least the safer practice, if not the common one. – kabanus Oct 22 '16 at 13:53
  • I prefer the first version. The function interface is simpler and similar to free(). Writing 0 to freed pointers may also hide double-free errors, errors which we want to find and fix. The second version may hide programming errors, not exactly best practise IMHO. – Bjorn A. Oct 22 '16 at 14:02
  • 1
    If the variable holding the pointer will stay around, setting it to NULL is a very good idea. The scheme you describe of calling `p = delete_simple(p)`, and having `delete_simple` always return NULL, is an interesting one. I've never seen anyone use that idiom. At first glance it looks like it might be cumbersome, but it might be worth it. – Steve Summit Oct 22 '16 at 14:03
  • I normally use a function like "void deleteMem(void **mem)". In deleteMem() check both "mem" and "*mem" for null. If they are not null, call "free(*mem);" and do "*mem = null". Instead of calling "free(mem)" in my project I call "deleteMem(&mem)". – MayurK Oct 22 '16 at 15:08

0 Answers0