Lap*_*pys 0 c++ memory-management
假设这样的代码:
#include <stdlib.h>
int main(int argc, char* argv[]) {
int value = 42;
void* pointer = (void*) &value;
// Free stack memory
free(pointer);
return 0;
}
Run Code Online (Sandbox Code Playgroud)
此代码导致未定义的行为,因为它尝试在堆栈上取消分配内存。
但是我在想;每次释放指针之前如何重新分配一个指针。
#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;
}
Run Code Online (Sandbox Code Playgroud)
我的假设是,这会将指针发送到堆内存,因此可以适当地释放它。
所有这些都是在程序员不知道在哪个内存(堆或堆栈)上指定了指针的情况下进行的(此时,程序的设计存在疑问,但我不会提出疑问)。
这是确保内存正确释放的安全方法,还是不适当的方法并在内存中创建了垃圾对象?
Joh*_*136 13
您无法realloc堆叠内存-因此您仍具有未定义的行为。
realloc(3)手册页将告诉您以下内容:
重新分配给定的内存区域。它必须事先由malloc(),calloc()或realloc()分配,并且尚未通过调用free或realloc进行释放。否则,结果是不确定的。
| 归档时间: |
|
| 查看次数: |
102 次 |
| 最近记录: |