1

I saw a simple C program:

//create a pointer to 3 bytes on heap
char *start = malloc(3);

*start = 'u';
*(start + 1) = 'v';
*(start + 2) = 'w';

printf("%s has %zu characters.\n", start, strlen(start));

// Free the memory so that it can be reused
free(start);
//Why we need to set start = NULL if we have already freed the memory above
start = NULL;

I understand everything except the last line start = NULL; , why we need to set it to NULL? Is it just to make the pointer point to a NULL instead of non-sense memory space?

Is start = NULL; a must action or nice-to-have action?

Rob
  • 415,655
  • 72
  • 787
  • 1,044
user842225
  • 5,445
  • 15
  • 69
  • 119
  • 2
    you have a bug in your code. Your string is not \0 terminated so strlen won't work. You should malloc 4 bytes and set the last to \0 for a string of length 3 – halex Feb 28 '15 at 15:47

1 Answers1

1

You ask:

Is start = NULL; a must action or nice-to-have action?

While not technically required, it's good programming practice to NULL the pointer to avoid having a "dangling pointer", a pointer to memory that no longer invalid.

If the start variable is immediately falling out of scope (i.e. the dangling pointer is going to immediately disappear), then this is of limited value. But if this start variable has a broader scope, it's best practice to NULL it.

Rob
  • 415,655
  • 72
  • 787
  • 1,044
  • You might benefit from reading answer 2 in the duplicate. Or you migh already know it's at best a bad attempt to sweep things under the carpet. – Deduplicator Feb 28 '15 at 16:20
  • Lol. That answer is absurd. At best, it's a straw man (no one asked "if I `NULL` my pointers, that fixes all my double `free` problems, right?"). – Rob Feb 28 '15 at 16:45
  • It's less about that specific failure-mode, and more about whether always nulling out pointers passed to free / delete / at definition time is a good idea. – Deduplicator Feb 28 '15 at 18:46