c++ - 删除和内存管理

标签 c++ memory memory-management

我发现运行以下(示例)代码的内存管理有意想不到的结果:

#include <stdint.h>
#include <iostream>
#include <vector>

#define BIGNUM 100000000

// sample struct
struct Coordinate {
    uint64_t x;
    uint64_t y;
    uint64_t z;
    Coordinate() {
        x = 1ULL;
        y = 2ULL;
        z = 3ULL;
    }
};

int main() {
    std::vector<Coordinate*>* coordinates = new std::vector<Coordinate*>();

    for (int i = 0; i < BIGNUM; ++i)
        coordinates->push_back(new Coordinate());

    // block 1
    for(std::vector<Coordinate*>::iterator it = coordinates->begin(); it != coordinates->end(); ++it)
        delete(*it);

    // block 2
    delete(coordinates);

    std::cout << "end\n";
    std::cin.get();

    return 0;
}

在我的 Ubuntu 14.04 上:

enter image description here

ps aux --sort -rss 命令在 std::cin.get(); 上执行了 4 次,但有细微差别:

1) 程序原样

2) 对 block 1 进行了注释(基本上没有删除每个 vector 的元素)

3) 对 block 2 进行了注释(因此不删除 vector)

4) block 1 和 block 2 都进行了评论。

我的(大)惊喜测试 1) 和 2) 有几乎相同的 RSS/VSZ 结果。简单来说,delete(*it); 似乎不能正常工作(不释放内存)。 3)和4)也可以得出同样的结论。

在 Windows XP 上(在 VirtualBox 中运行)一切正常,内存为 0-2 MB,按原样运行程序。

最佳答案

仅仅因为delete 释放内存并不意味着内存会立即释放回操作系统以供一般使用。现代操作系统上的内存管理是 just not that simple .

除了您的假设,这里没有任何问题!

关于c++ - 删除和内存管理,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31905386/

相关文章:

ios - 内存泄漏 - UIImagePNGRepresentation

c++ - c 和 c++ 运算符帮助

c++ - 在不迭代的情况下在两个映射中找到公共(public)值

c# - 通过 Span<T> 修改变量时,优化构建和 JIT 编译会产生问题吗?

Eclipse内存分配问题

ios - 当 block 内的 ivar 可能被释放时,管理内存的最佳方法是什么?

c++ - 使用使用 C 样式字符串作为 OUT 参数的 WinAPI 函数

c++ - 从 istream 中提取失败后的字符串内容

java - 内存中的文件是否与文件系统中的文件大小相同?

c++ - 试图从内存中删除字符串。不会让我分配给 cin