我可能已经宣誓过,这段代码应该可以工作,但是现在看来它是段错误的。有人知道这是否总是如此,还是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.
此代码段
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释放了空间,则该行为是undefined。
你可以写
tmp = &tmp[10];
//...
free(tmp - 10 );
或者似乎您需要重新分配早期分配的内存,例如
char *tmp = malloc(50);
char *tmp2 = realloc( tmp, 10 );
if ( tmp2 != NULL ) tmp = tmp2;
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句