为什么我在C++中有一个空指针取消引用

Why do I have a null pointer dereference in C++?

本文关键字:空指针 取消 引用 有一个 C++ 为什么      更新时间:2023-10-16

我在 Eclipse 中收到空指针取消引用,我不知道如何准确修复此错误。

以下是日志错误:

04-18 10:27:48.538: A/DEBUG(22481): Build fingerprint: 
'OnePlus/OnePlus3/OnePlus3T:8.0.0/OPR6.170623.013/12041042:user/release- keys'
04-18 10:27:48.538: A/DEBUG(22481): Revision: '0'
04-18 10:27:48.538: A/DEBUG(22481): ABI: 'arm'
04-18 10:27:48.538: A/DEBUG(22481): pid: 22024, tid: 22078, name: GLThread     8317  >>>  <<<
04-18 10:27:48.538: A/DEBUG(22481): signal 11 (SIGSEGV), code 1     (SEGV_MAPERR), fault addr 0x0
04-18 10:27:48.538: A/DEBUG(22481): Cause: null pointer dereference
04-18 10:27:48.538: A/DEBUG(22481):     r0 b9bb0e74  r1 00000000  r2     00000001  r3 00000000
04-18 10:27:48.538: A/DEBUG(22481):     r4 000aa185  r5 afdd0c28  r6     b9bb1a40  r7 b9b83a40
04-18 10:27:48.538: A/DEBUG(22481):     r8 0000cf00  r9 000ac440  sl     00000000  fp 0000ac44
04-18 10:27:48.538: A/DEBUG(22481):     ip 000bdcc0  sp c1bfe1b0  lr     c25fd079  pc c25fd084  cpsr 08070030
04-18 10:27:48.541: A/DEBUG(22481): backtrace:
04-18 10:27:48.541: A/DEBUG(22481):     #00 pc 0022d084      /data/app/com.-xBYgyq_62u2R3qWK0qBgkQ==/lib/arm/libgame.so     (_ZN12CSoundSource12GetAudioDataEPfii+87)

并且错误发生在代码的这一部分:

void CSoundSource::GetAudioData(float *data, int frameStart, int frames)
{
int i=0;
while(i<frames)
    {
    int temp_samp = (frameStart+i) % TotalSamples;
    int tmp_div = temp_samp / blockSize;
    int tmp_mod = temp_samp % blockSize;
        *data = block[tmp_div]->buffer[tmp_mod][0] * 0.00003f;
    data++;
        *data = block[tmp_div]->buffer[tmp_mod][1] * 0.00003f;
    data++;
    i++;
    }
}

有人可以告诉我如何修复空取消引用吗?或者给一个提示,为我指出正确的方向?

谢谢。

我发现了问题。

显然,崩溃是由于block[tmp_div]为空而引起的。在*data = block[tmp_div]->buffer[tmp_mod][0] * 0.00003f;之前,另一个线程没有为其分配值,因此我必须检查每个block[]以查看它是否为 NULL,如果是,则尝试再次为其提供正确的值。

因此,我发布的代码部分如下所示:

void CSoundSource::GetAudioData(float *data, int frameStart, int frames)
{
    int i=0;
    while(i<frames)
    {
        int temp_samp = (frameStart+i) % TotalSamples;
        int tmp_div = temp_samp / blockSize;
        int tmp_mod = temp_samp % blockSize;
        if(block[tmp_div])
            *data = block[tmp_div]->buffer[tmp_mod][0] * 0.00003f;
        data++;
        if(block[tmp_div])
            *data = block[tmp_div]->buffer[tmp_mod][1] * 0.00003f;
        data++;
        i++;
    }
}