Search code examples
c++alsa

it crash when I use ALSA lib's function `snd_pcm_readi`


This is the function which I read data from micro, but why when I allocate buffer by call new, the application crash, if I use malloc, it ok

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;
}

Solution

  • new char(bufSize) allocates a single char and initializes it to bufSize. You want new char[bufSize]. And when you new[] something, you must delete[] it later, not free it.

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

    To avoid having to manage memory manually, you could use std::unique_ptr or std::vector.

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

    Or

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