c++ - 在释放内存之前总是重新分配内存是否安全 - C++

标签 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;
}

此代码导致未定义的行为,因为它试图取消分配堆栈上的内存。


但我想知道;每次我们释放它之前重新分配一个指针怎么样。

#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/

相关文章:

c++ - Turbo C++ 和代码块

c++ - 关于结构的警告 C26495?

c++ - 取消引用被转换为双指针的指针

C内存池存储

c - 渐进式内存分配策略

c++ - 在 win 7 64 位的 visual studio 2012 中编写 x86 汇编代码的问题

c++ - 可以在没有模板参数的情况下使用模板类的静态类函数吗?

c - malloc() 使用 brk() 还是 mmap()?

c++ - 无法弄清楚如何使用 C++ 中的链表按从 a 到 z 的顺序显示字母表

memory-management - 减少RabbitMQ内存使用