考虑下面的代码:
#include < stdio.h >
#include < stdlib.h >
#define SIZE 10
int main() {
int * p, i;
p = malloc(SIZE * sizeof(int));
if (p == NULL) {
printf("malloc failed.\n");
return 1;
}
for (i = 0; i < SIZE; i++)
* (p + i) = i * i;
for (i = 0; i < SIZE; i++)
printf("%d\n", * p++);
free(p);
return 0;
}
该代码不起作用。但我不知道为什么。我的教授给出了一个对我来说没有多大意义的解释。据说free
功能不起作用。
据我了解,您只能释放使用 malloc 创建的指针。在这里,我们在将指针发送到 free 之前修改了该指针,从而使我们的语句无效。
这是批评该代码的正确方法吗?
最佳答案
And here we modify that pointer before sending it to free, thereby making our statement invalid.
Is this the correct way to critique that code?
是的,代码没有释放由于 p++
分配的原始指针,它会在每次循环迭代时递增指针。
相反,以不改变 p
的方式打印。
for (i = 0; i < SIZE; i++) {
// printf("%d\n", * p++);
printf("%d\n", p[i]);
// or
printf("%d\n", * (p + i));
}
// With above change, `p` is the same as the original allocated value.
free(p);
关于c - 使用 Malloc 和 Free 调试指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50108609/