我在尝试使用 realloc 重新分配内存时在 C 代码中遇到警告。具体警告是:
lib/gc.c: In function ‘gcLocalRealloc’:
lib/gc.c:625:9: warning: pointer ‘old’ may be used after ‘realloc’ [-Wuse-after-free]
625 | gcLocalPop ( gc,old ) ;
| ^~~~~~~~~~~~~~~~~~~~~
lib/gc.c:621:11: note: call to ‘realloc’ here
621 | ptr = (void*) realloc ( ptr,SIZE ) ;
这是导致问题的代码:
void* gcLocalRealloc(gc_t *gc, void* ptr, size_t SIZE) {
//assert(SIZE!=0); // realloc(array, 0) is not equivalent to free(array).
if (SIZE == 0) {
gcFree(ptr);
return ptr = NULL;
}
assert(SIZE > 0);
if (ptr == NULL) return gcLocalMalloc(gc, SIZE);
void* old = ptr;
ptr = (void*) realloc(ptr, SIZE);
if (ptr != NULL) {
gcLocalPop(gc, old);
gcLocalPush(gc, ptr, SIZE);
assert(ptr != NULL);
}
return ptr;
}
编译器警告指针 old 被 realloc 释放后可能会被使用。如何修复此警告,同时保持重新分配内存和更新垃圾收集的功能?
预先感谢您的帮助!
一旦调用
realloc
,如果它返回非空值,那么 old
的值(包含先前的指针值)将变为 不确定。 因此,尝试使用此值(即使您不取消引用它)可能会导致未定义的行为。
在这种情况下,你应该做的是在调用
gcLocalPop
之前先调用realloc
,无论成功与否,只需调用gcLocalPush
即可。
void* gcLocalRealloc(gc_t *gc, void* ptr, size_t SIZE) {
//assert(SIZE!=0); // realloc(array, 0) is not equivalent to free(array).
if (SIZE == 0) {
gcFree(ptr);
return ptr = NULL;
}
assert(SIZE > 0);
if (ptr == NULL) return gcLocalMalloc(gc, SIZE);
gcLocalPop(gc, ptr);
void* old = ptr;
ptr = (void*) realloc(ptr, SIZE);
if (ptr != NULL) {
gcLocalPush(gc, ptr, SIZE);
return ptr;
} else {
gcLocalPush(gc, old, SIZE);
return old;
}
}