在我的应用程序中,我正在分配内存来存储从位图图像堆栈中读取的“体积数据”。
我将数据存储在“无符号字符”中,并且在分配期间,首先我尝试为整个数据分配连续的内存块。如果失败,然后尝试分散分配。(每个图像一个小内存块)。
unsigned char *data;
这是我分配内存的方法,我用“tryContinuseBlock = 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 位平台上运行。
现在的问题是,即使在 64Bit 环境(具有 12Gb 内存)中,当我加载 (1896*1816*1253) 大小的数据(bbpsize=1)时, helper_allocContinouseVolume()方法也会失败。这是因为,我使用“int”数据类型进行内存地址访问,“int”的最大值为 4294967295。
在 32 位和 64 位环境中,以下代码给出了值“19282112”。
int sx=1896;
int sy=1816;
int sz=1253;
printf("%d",sx*sy*sz);
其中正确的值应该是“4314249408”。
那么我应该使用哪种数据类型呢?我想在 32 位和 64 位环境中使用相同的代码。