当我使用ALSA lib的函数`snd_pcm_readi`时崩溃

时间:2017-08-01 06:38:16

标签: c++ alsa

这是我从micro读取数据的函数,但是为什么当我通过调用new分配缓冲区时,应用程序崩溃,如果我使用malloc,则确定

void AlsaMicrophoneWrapper::readThreadFunction()
{
    int bufSize = m_bitsPerFrame * m_frames; 
    // char *buf = new char(bufSize);//crash
    char *buf = (char *)malloc(bufSize);
    if (NULL == buf)
    {
        printf("Snd_ReadThread allocate mem error\n");
        return;
    }
    snd_pcm_sframes_t retFrame;
    ssize_t returnCode;
    while (true)
    {
        retFrame = snd_pcm_readi(m_pcmHandle, buf, m_frames);
        if (-EPIPE == retFrame)
        {
            snd_pcm_prepare(m_pcmHandle);
        }
        else if (retFrame > 0)
        {
            returnCode = m_writer->write(buf, retFrame);
            if (returnCode <= 0)
            {
                printf("Failed to write to stream.\n");
            }
        }
    }

    free (buf);
    return;
}

1 个答案:

答案 0 :(得分:4)

new char(bufSize)分配一个char并将其初始化为bufSize。你想要new char[bufSize]。当你new[]某事时,你必须稍后delete[],而不是free

char *buf = new char[bufSize];
...
delete[] buf;

为避免手动管理内存,您可以使用std::unique_ptrstd::vector

auto buf = std::make_unique<char[]>(bufSize);
// use buf.get() to access the allocated memory

或者

std::vector<char> buf(bufSize);
// use buf.data() to access the allocated memory