释放堆内存后将指针设置为 NULL

set pointer to NULL after free the heap memory

我看到了一个简单的C程序:

//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;

除了最后一行start = NULL;我都明白了,为什么我们要把它设置成NULL?难道只是为了让指针指向一个NULL而不是无意义的内存space?

start = NULL; 是必须采取的行动还是可有可无的行动?

你问:

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

虽然在技术上没有要求,但 NULL 指针是一个很好的编程习惯,可以避免 "dangling pointer",指向不再无效的内存的指针。

如果 start 变量立即超出范围(即悬空指针将立即消失),那么它的价值有限。但是,如果此 start 变量的范围更广,则最好 NULL 它。