c - 使用 Malloc 和 Free 调试指针

标签 c debugging gdb

考虑下面的代码:

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

相关文章:

c - 线程中的私有(private)变量

c - X : trigger events at fixed intervals

java - 如何查看线程在代码java中的位置

c - 如何让 gdb 显示关于函数头部的行号?

c - 在 if 语句之外保留并打印值

c - 在linux上的c中分配可执行ram

python - 在 Python 调试器 pdb 中,如何在不终止调试 session 的情况下退出交互模式

windows - 什么是 “Cannot set allocations”错误,由谁发出,我该怎么办?

c++ - 我的应用程序可以安排 gdb 断点或观察吗?

c - 结构值以意想不到的方式从一个函数更改为另一个函数