假设代码如下:
#include <stdlib.h>
int main(int argc, char* argv[]) {
int value = 42;
void* pointer = (void*) &value;
// Free stack memory
free(pointer);
return 0;
}
此代码导致未定义的行为,因为它试图取消分配堆栈上的内存。
但我想知道;每次我们释放它之前重新分配一个指针怎么样。
#include <stdlib.h>
int main(int argc, char* argv[]) {
int value = 42;
void* pointer = (void*) &value;
// Allocate pointer on heap, then free memory
pointer = realloc(pointer, sizeof pointer);
free(pointer);
return 0;
}
我的假设是这会将指针发送到堆内存,以便可以适本地释放它。
所有这一切都与程序员不知道指针指定在哪个内存(堆或堆栈)上的上下文有关(此时,程序的设计受到质疑,但我不会离题) .
查询
这是确保内存被正确释放的安全方法还是它是否不合适并创建内存中留下的垃圾对象?
最佳答案
你不能realloc
堆栈内存 - 所以你仍然有未定义的行为。
realloc(3) 手册页会告诉您:
Reallocates the given area of memory. It must be previously allocated by malloc(), calloc() or realloc() and not yet freed with a call to free or realloc. Otherwise, the results are undefined.
关于c++ - 在释放内存之前总是重新分配内存是否安全 - C++,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55250458/