0

为了了解更多关于指针的信息,我只写了一个简单的测试函数,它创建一个指针,在 shell 上的一些输出之后分配空间,并且应该释放空间。

void main() {
  int *p = (int*) malloc(sizeof(int));
  int a = 42;
  printf("p: %x\n", p);
  printf("*p: %d\n", *p);
  printf("a: %s\n", a);
  printf("&a: %x\n", &a);
  p = &a;
  printf("p: %x\n", p);
  printf("*p: %x\n", *p);

  //Until now everything works as expected
  free(p); //ERROR
  // printf("p: %x\n", p); // Shall cause error, because space was freed
  // printf("*p: %x\n", *p); // Shall cause error, because space was freed
}

起初运行一切正常。free(p) 没有导致错误。然后我用一个结构尝试了同样的测试,得到了双重释放错误。“好吧,也许我做错了什么,让我们开始吧”,我想,然后按 Ctrl+Z 把上面的所有内容都移到上面,就像以前一样。现在我仍然得到这个错误。为什么?这是一个新手问题,我知道。上面的代码在网络上随处可见,作为 malloc 和 free 的简单演示。喜欢这里:http ://www.cplusplus.com/reference/cstdlib/free/ 希望,有人可以告诉我我做错了什么。

4

2 回答 2

3

传递给的指针必须从先前调用(or or ) 中返回。这与 after 的地址不同:free() malloc()calloc()realloc()pa

p = &a;

然后p传递给free()导致未定义的行为。

请注意,在问题中链接的页面示例中,指针在调用任何动态分配函数后都没有被重新分配。


"Shall cause error, because space was freed"以下代码段中的注释不正确:

free(p); //ERROR
// printf("p: %x\n", p); // Shall cause error, because space was freed

因为打印指针的地址是安全的,无论它关联的内存是否存在free()。如果你试图访问已经被 d 的内存free()错误的,所以这个注释是正确的:

// printf("*p: %x\n", *p); // Shall cause error, because space was freed

因为p正在被推迟并且正在尝试读取free()d 内存。


这是一个错误:

printf("a: %s\n", a); /* Must be '%d' as 'a' is an 'int'. */

注意:

printf("p: %x\n", p);

也是未定义的行为:%p对指针使用格式说明符。请参阅正确的格式说明符以打印指针(地址)?


我要转换 malloc 的结果吗?

于 2013-05-04T19:27:22.887 回答
0
void main() {
  int *p = (int*) malloc(sizeof(int));   // here is error number one.
                                         // you casted your fresh malloc'd int
                                         // to an int*
                                         // which is not what you want to do
                                         // get rid of the cast you don't need it.

   // here is where your problem continues.
  int a = 42;   // this variable A was created on the stack not the heap!!
                //you cant free this, which is what you are doing below.
  printf("p: %x\n", p);
  printf("*p: %d\n", *p);
  printf("a: %s\n", a);
  printf("&a: %x\n", &a);

  p = &a; // this is a correct statement. 
          // you getting the address of var a
          // and making pointer p point to A's contents.
  printf("p: %x\n", p);
  printf("*p: %x\n", *p);

  //Until now everything works as expected
  free(p); //ERROR: here you are trying to free var A 
           // but you cant because it wasnt dynamically allocated.
  // printf("p: %x\n", p); // Shall cause error, because space was freed
  // printf("*p: %x\n", *p); // Shall cause error, because space was freed
}

希望这个对你有帮助。我强烈建议您阅读 K&R(Kernegie and Richie) C 编程语言书籍中关于指针的 CH 5。它真的很短,您可能可以在某处免费在线找到它。事实上,我建议你阅读整本书。最好的c书。请记住,您只能释放您分配的内容(请记住,每个 malloc 都会从堆中为您提供内存块)

于 2013-05-04T20:08:03.023 回答