奇怪的EXC_BAD_ACCESS

时间:2011-12-27 19:30:12

标签: iphone objective-c exc-bad-access

我的Objective-C代码中有一个for循环,不断抛出 EXC_BAD_ACCESS 错误。这是代码:

double (*X)[2];

for (int bufferCount=0; bufferCount < audioBufferList.mNumberBuffers; bufferCount++) {
    SInt16* samples = (SInt16 *)audioBufferList.mBuffers[bufferCount].mData;
    for (int i=0; i < 1024; i+=2){//numSamplesInBuffer / 2; i+=2) {
        X[i][0] = samples[i];
        X[i][1] = samples[i + 1];

        NSLog(@"left: %f", X[i][0]);
        NSLog(@"right: %f", X[i][1]);
        NSLog(@"i: %d", i);
    }
}

i = 385时,我在第EXC_BAD_ACCESS行获得 NSLog(@"left: %f:", X[i][0]);

认为在本地声明 X 可能是内存问题,我将 X 更改为导致 EXC_BAD_ACCESS 第一次通过for循环的第一行。

有人知道为什么会这样吗?

2 个答案:

答案 0 :(得分:2)

double X[512][2];

for (int bufferCount=0; bufferCount < audioBufferList.mNumberBuffers; bufferCount++) {
    SInt16* samples = (SInt16 *)audioBufferList.mBuffers[bufferCount].mData;
    for (int i=0; i < 512; i++) {
        int sample_offset = i * 2;
        X[i][0] = samples[sample_offset];
        X[i][1] = samples[sample_offset + 1];

        NSLog(@"left: %f", X[i][0]);
        NSLog(@"right: %f", X[i][1]);
        NSLog(@"i: %d", i);
    }
}

答案 1 :(得分:0)

正如HotLicks指出的那样,问题在于我没有为数组分配任何空间。解决方案是像这样初始化数组:

double (*X)[2] = malloc(2 * 1024 * sizeof(double));