c++ - c++ 中新分配的 int 的内存大小,有没有更好的不同方式来查看它?

标签 c++ memory size allocation

在这个程序中,我试图找出为我的指针分配了多少内存。我可以通过这种方式看到它应该是 1 gibibyte,即 = 1 073 741 824 字节。我的问题是,我可以通过的唯一方法是将 int 的大小设为 4,然后乘以该 const 数。有什么不同的方法吗?

#include "stdafx.h"
#include <iostream>
#include <new>

int main(){

    const int gib = 268435256; //Created a constant int so I could allocate 1 
                           //Gib memory
    int *ptr = new int [gib];

    std::cout << sizeof (int)*gib << std::endl;
    std::cout << *ptr << std::endl;
    std::cout << ptr << std::endl;

    try {
    }catch (std::bad_alloc e) {
        std::cerr << e.what() << std::endl;
    }

    system("PAUSE");
    delete[] ptr;

    return 0;
}

最佳答案

不,没有办法。编译器在内部添加了有关分配了多少内存以及由 new[] 创建了多少元素的信息。 ,否则它无法执行 delete[]正确。但是,在 C++ 中没有可移植的方法来获取该信息并直接使用它。

所以你必须在你仍然知道尺寸的时候单独存储它。

实际上,你不需要,因为std::vector为你做:

#include <iostream>
#include <vector>
#include <new>

int main() {

    const int gib = 268435256;

    try {
        std::vector<int> v(gib);
        std::cout << (v.capacity() * sizeof(int)) << '\n';
    } catch (std::bad_alloc const& e) {
        std::cerr << e.what() << '\n';
    }
}

你几乎不应该使用 new[] .使用 std::vector .


请注意,我使用了 capacity而不是 size ,因为 size告诉您 vector 代表多少项,该数字可以小于 vector 当前分配的内存支持的元素数。

也没有办法避免 sizeof ,因为 int 的大小可以因实现而异。但这也不是问题,因为 std::vector不会丢失其类型信息,因此您始终知道一个元素有多大。

如果它是 std::vector<char>,则不需要乘法, 一个 std::vector<unsigned char>std::vector<signed char> ,因为这三种字符类型' sizeof保证为 1。

关于c++ - c++ 中新分配的 int 的内存大小,有没有更好的不同方式来查看它?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49830318/

相关文章:

C 访问另一个程序内存?

java - 如何读取 Java 中序列化对象的大小(以字节为单位)?

c++ - 实现手写动态数组的插入数组方法 - C++

java - 通过 Java 使用 Selenium Webdriver 缺少 size() 选项

c++ - VC++6显示中文

c++ - OpenMP:无法并行化嵌套的 for 循环

c++ - 将 bash 命令添加到 CMake 测试中

c++ - 类方法变量,如果我将它们存储在类本身中会更快吗?

performance - 内存基准图 : understanding cache behaviour

c++ - 将服务器响应(std::string)转换为 png 文件