【发布时间】:2015-05-01 06:05:14
【问题描述】:
我看到了一个简单的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 而不是无意义的内存空间?
start = NULL; 是必须采取的行动还是必须采取的行动?
【问题讨论】:
-
您的代码中有错误。您的字符串不是 \0 终止的,因此 strlen 将不起作用。您应该 malloc 4 个字节并将最后一个设置为 \0 以获取长度为 3 的字符串
标签: c memory-management malloc free