首页 > 解决方案 > 自由指针偏移不再有效?

问题描述

我本可以发誓这段代码应该可以工作,但现在看来它出现了段错误。任何人都知道这是一直如此还是glibc的变化?


   ....
   char *tmp = malloc(50);
   tmp = &tmp[10];
   free(tmp);   // segfault
   // I thought as long as the pointer was within a valid memory block,   
   // the free was valid. Obviously I know not to double free, but this   
   // means any pointer offsets must be kept along with the original malloced 
   // pointer for the free operation.

标签: cdynamic-memory-allocationfreeglibcpointer-arithmetic

解决方案


此代码段

   char *tmp = malloc(50);
   tmp = &tmp[10];
   free(tmp);   // segfault
   // I thought as long as the

无效,因为在此语句之后

   tmp = &tmp[10];

指针 tmp 没有动态分配的内存范围的地址。所以下一个语句

free(tmp);

调用未定义的行为。

来自 C 标准(7.22.3.3 自由函数)

否则,如果参数与内存管理函数先前返回的指针不匹配,或者如果空间已通过调用 free 或 realloc 被释放,则行为未定义

你可以写

   tmp = &tmp[10];
   //...
   free(tmp - 10 );

或者您似乎需要重新分配早期分配的内存,例如

   char *tmp = malloc(50);
   char *tmp2 = realloc( tmp, 10 );

   if ( tmp2 != NULL ) tmp = tmp2;

推荐阅读