自由指针偏移量不再有效?
Free pointer offset no longer valid?
我发誓这段代码应该可以工作,但现在看来它有段错误。任何人都知道这种情况是否一直如此或 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自由函数)
否则,如果参数与内存管理函数先前返回的指针不匹配,或者如果 space 已通过调用 free 或重新分配,行为未定义。
你可以写
tmp = &tmp[10];
//...
free(tmp - 10 );
或者您似乎需要像
一样重新分配早期分配的内存
char *tmp = malloc(50);
char *tmp2 = realloc( tmp, 10 );
if ( tmp2 != NULL ) tmp = tmp2;
我发誓这段代码应该可以工作,但现在看来它有段错误。任何人都知道这种情况是否一直如此或 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自由函数)
否则,如果参数与内存管理函数先前返回的指针不匹配,或者如果 space 已通过调用 free 或重新分配,行为未定义。
你可以写
tmp = &tmp[10];
//...
free(tmp - 10 );
或者您似乎需要像
一样重新分配早期分配的内存 char *tmp = malloc(50);
char *tmp2 = realloc( tmp, 10 );
if ( tmp2 != NULL ) tmp = tmp2;