3

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

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

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 位环境中使用相同的代码。

4

3 回答 3

2

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

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

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

于 2011-09-28T06:27:25.100 回答
1

使用ptrdiff_t<stddef.h>.

原因:它是有符号的,因此避免了涉及无符号的隐式提升的问题,并且它在除 16 位之外的任何系统上都有必要的范围(在形式上它在 16 位上也能很好地工作,但那是因为形式有至少 17 个(原文如此)位的愚蠢要求)。

于 2011-09-28T06:55:11.940 回答
1

size_t被定义为足够大以描述最大的有效对象大小。所以一般来说,在分配对象时,这是要使用的正确大小。

ptrdiff_t被定义为能够描述任意两个地址之间的差异。

使用适合您目的的那个。这样你就可以确保它有合适的尺寸。

于 2011-09-28T07:10:24.703 回答