Xcode 5.0.1 中未报告分段错误

Segmentation fault not reported in Xcode 5.0.1

本文关键字:报告 分段 错误 Xcode      更新时间:2023-10-16

我一直在调试一段代码,很难发现我的错误之一。我已经声明并像数组一样

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 的工具可以帮助我进行调试?

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

您可以打开 malloc 涂鸦并保护 malloc 以帮助查找其中一些问题。您还可以使用仪器和 clang 静态分析器。