自由指针偏移不再有效?

问题描述 投票:3回答:1

我可能已经宣誓过,这段代码应该可以工作,但是现在看来它是段错误的。任何人都知道这是否总是如此,还是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.
c dynamic-memory-allocation free glibc pointer-arithmetic
1个回答
1
投票

此代码段

   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;
    
© www.soinside.com 2019 - 2024. All rights reserved.