gpt4 book ai didi

c++ - 分配大量内存和使用 size_t?

转载 作者:太空狗 更新时间:2023-10-29 21:06:32 25 4
gpt4 key购买 nike

在我的应用程序中,我正在分配内存来存储从位图图像堆栈中读取的“体积数据”。

我将数据存储在“unsigned char”中,并且在分配期间,首先我尝试为整个数据分配连续的内存块。如果失败,则尝试分散分配。(每个图像一个小内存块) .

unsigned char *data;

这是我分配内存的方法,我用“tryContinouseBlock=true”调用。

 bool RzVolume::initVolumeData(int xsize, int ysize, int zsize, int bbpsize,bool tryContinouseBlock) {
this->nx = xsize;
this->ny = ysize;
this->nz = zsize;
this->bbp_type=bbpsize;

bool succ = false;

if (tryContinouseBlock) {
succ = helper_allocContinouseVolume(xsize, ysize, zsize, bbpsize);
}

if (!succ) {
succ = helper_allocScatteredVolume(xsize, ysize, zsize, bbpsize);
} else {
isContinousAlloc = true;
}
if (!succ) {
qErrnoWarning("Critical ERROR - Scattered allocation also failed!!!!");
}
return succ;

}



bool RzVolume::helper_allocContinouseVolume(int xsize, int ysize, int zsize,
int bbpsize) {
try {
data = new unsigned char*[1];
int total=xsize*ysize*zsize*bbpsize;
data[0] = new unsigned char[total];
qDebug("VoxelData allocated - Continouse! x=%d y=%d Z=%d bytes=%d",xsize,ysize,zsize,xsize * ysize * zsize * bbpsize);
} catch (std::bad_alloc e) {
return false;
}

return true;

}

bool RzVolume::helper_allocScatteredVolume(int xsize, int ysize, int zsize,
int bbpsize) {
data = new unsigned char*[zsize];
//isContinousAlloc=false;
int allocCount = 0;
try { //Now try to allocate for each image
for (int i = 0; i < zsize; i++) {
data[i] = new unsigned char[xsize * ysize];
allocCount++;
}
} catch (std::bad_alloc ee) {
//We failed to allocated either way.Failed!

//deallocate any allocated memory;
for (int i = 0; i < allocCount; i++) {
delete data[i];
}
delete data;
data = NULL;
return false;
}
qDebug("VoxelData allocated - Scattered!");
return true;
}

我希望此代码在 32 位和 64 位平台上运行。

现在的问题是,即使在 64 位环境(具有 12Gb 内存)中,helper_allocContinouseVolume() 方法在我加载 (1896*1816*1253) 大小的数据(bbpsize=1)时失败。这是因为,我使用“int”数据类型进行内存地址访问,“int”的最大值为 4294967295。

在 32 位和 64 位环境中,以下代码给出值“19282112”。

 int sx=1896;
int sy=1816;
int sz=1253;
printf("%d",sx*sy*sz);

正确的值应该是“4314249408”。

那么我应该使用哪种数据类型呢?我想在 32 位和 64 位环境中使用相同的代码。

最佳答案

在内存大于 32GB 和大型数据集的工作站上工作时,我经常遇到同样的问题。

size_t 通常是用于所有索引的正确数据类型,因为它“通常”匹配指针大小并与 memcpy() 和其他库保持兼容功能。

唯一的问题是在 32 位上,可能很难检测到溢出的情况。因此,可能值得使用一个单独的内存计算阶段,使用最大整数大小来查看它是否可能在 32 位上,以便您可以优雅地处理它。

关于c++ - 分配大量内存和使用 size_t?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7579112/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com