C++ 内存分配错误?

c++ Memory allocated wrong?

本文关键字:错误 分配 内存 C++      更新时间:2023-10-16

我已经在一行代码上工作了三天,我发现分配的内存似乎不像我想象的那样。

我有一个Buffer类,它拥有两个int变量和一个*float指针,我认为它在内存中占用了 16 个字节。

我还有一个Film类,其中包含两个int变量、两个Vec3f变量和一个Buffer*指针。Vec3f是一个包含三个float变量的类。

类定义如下:

class Buffer {
public:
int _width;
int _heigth;
Vec3f *_data;
Buffer(int w, int h) : _width(w), _height(h) {
_data = new Vec3f(_width*_heigth);
}
~Buffer();
};
struct Film {
int _width;
int _height;
Vec3f _left_bottom_corner;
Vec3f _left_up_corner;
Buffer *_cbuffer;
Film(int w, int h, Buffer *cbuffer) : _width(w), _height(h), _cbuffer(cbuffer) {}   
};
template<typename ElementType, unsigned Size>
class Vector {
private:
std::array<ElementType, Size> _v;
};
typedef Vector<float, 3> Vec3f;

我像这样初始化它们:

int w = 5; int h = 5;
Buffer *b = new Buffer(w, h);
Film *film = new Film(w, h, b);

当我尝试为film->_cbuffer->data[i]赋值时发生了一些奇怪的事情,所以我调试了程序

std::cout << b << std::endl;
std::cout << b->_data << std::endl;
std::cout << film << std::endl;

输出为

0x7fa500500000
0x7fa500600000
0x7fa500600010

我认为一个Buffer实例应该占用 16 个字节,一个Film实例应该占用最多4*2 + 4*3*2 + 8字节。但真正重要的是Buffer._data数组的大小,我用new运算符手动分配了它。

从给定的结果来看,数组最多占用 16 个字节,这对于我测试过的所有wh都是固定的,这不是我想象的。以w=5, h=5为例,数组的大小应该是5 * 5 * 8

对于像这样分配的内存,film._width将在以下情况下进行修改 当wh都设置为1时,内存被意外地分配为"正确":

0x7f90b9d00000
0x7f90b9d00010
0x7f90b9d00020

你在这里没有看到问题吗?

Buffer(int w, int h) {
_data = new Vec3f(_width*_heigth);
}

使用未初始化的_width_heigth不奇怪吗?可能你想要:

Buffer(int w, int h): _width(w), _heigth(h) {
_data = new Vec3f[_width*_heigth];
}

下面的行输出_data指向Vec3f数组的地址。

std::cout << b->_data << std::endl;

如果要查看Buffer对象中_data的地址,它应该是

std::cout << &b->_data << std::endl;

new Vec3f(_width*_heigth)不初始化任何可变长度的数组。数组字段的大小始终Vec3f3,这可能不是缓冲区构造函数中您想要的。顺便说一句,你根本没有任何Vector::Vector(some_kind_of_int)构造函数。

您可能想在缓冲区中使用(运行时已知大小)std::vector,而不是基于(编译时已知常量 (AKAconstexpr) 长度)std::array的内容。