0

我一直在调试一个很难发现我的错误的代码。我已经声明和数组喜欢

char* Cdiff[320];

然而,当在 Xcode 5.0.1 中运行应用程序时,它在代码的其他部分崩溃(根据我的说法)与该数组没有任何关系。

我正在使用的代码示例是

...
...
//patchSize = 4, blockSize = 10
uchar *Cdiff = new uchar[(patchSize*patchSize)*2 * blockSize];

// FOR EACH BLOCK OF PATCHES (there are 'blockSize' patches in one block)
for (uint iBlock = 0; iBlock < nBlocks; iBlock++)
{
    // FOR EACH PATCH IN THE BLOCK
    for(uint iPatch = iBlock*blockSize; iPatch < (iBlock*blockSize)+blockSize; iPatch++)
    {
        // GET THE POSITION OF THE upper-left CORNER(row, col) AND
        // STORE THE COORDINATES OF THE PIXELS INSIDE THE CURRENT PATCH (only the current patch)
        uint iPatchV = (iPatch*patchStep)/camRef->getWidth();
        uint iPatchH = (iPatch*patchStep)%camRef->getWidth();
        for (uint pRow = iPatchV, pdRow = 0; pRow < iPatchV+patchSize; pRow++, pdRow++)
        {
            for (uint pCol = iPatchH, pdCol = 0; pCol < iPatchH+patchSize; pCol++, pdCol++)
            {
                patchPos.push_back(Pixel(pCol, pRow));
            }
        }

        // GET THE RIGHT AND DOWN NEIGHBORS TO COMPUTE THE DIFFERENCES
        uint offset = 0;
        for (Pixel p : patchPos)
        {
            uint r = p.getY();
            uint c = p.getX();

            uchar pixelV = ((uchar*)camRef->getData())[r*imageW+c];

            uint cRightNeighbor = c+patchStep;
            uchar pixelVrightP = 0;

            if (cRightNeighbor < imageW)
            {
                pixelVrightP = abs(pixelV - ((uchar*)camRef->getData())[r*imageW+cRightNeighbor]);
            }

            uint rDownNeighbor = r+patchStep;
            uchar pixelVbelowP = 0;

            if (rDownNeighbor < imageH)
            {
                pixelVbelowP = abs(pixelV - ((uchar*)camRef->getData())[rDownNeighbor*imageW+c]);
            }

            //---This is the right way to compute the index.
            int checking = (iPatch%blockSize)*(patchSize*patchSize)*2 + offset;
            //---This lines should throw a seg_fault but they don't
            Cdiff[iPatch*(patchSize*patchSize)*2 + offset] = pixelVrightP;
            Cdiff[iPatch*(patchSize*patchSize)*2 + offset+(patchSize*patchSize)] = pixelVbelowP;
            offset++;
        }

        ...
        ...

    }
}         

我忘记blockSize在索引的计算中使用,所以在块的每次迭代中,它从第 0 个位置开始写入。

谁能解释我如何/为什么没有正确报告 Xcode 这些类型的 seg_faults?实际上,我必须测试我的代码并在 linux 上对其进行调试,以便能够捕获该错误。Xcode 中是否有类似于 Valgrid 的工具可以帮助我调试?

4

1 回答 1

1

只有当您的代码访问不属于它或不存在的内存时,您才会收到段错误。因为CDiff在堆上,所以在它之前和之后可能有你的进程拥有和访问的内存,但尚未分配。所以没有段错误是有道理的。(它也可能是为其他变量分配给您的内存,因此您正在覆盖该变量,但它直到后来才出现。)

您可以打开malloc scribbling 和 guard malloc来帮助找到其中一些问题。您还可以使用Instrumentsclang 静态分析器

于 2013-11-03T17:17:08.097 回答