【问题标题】:it crash when I use ALSA lib's function `snd_pcm_readi`当我使用 ALSA lib 的函数 `snd_pcm_readi` 时它崩溃了
【发布时间】:2018-01-07 21:27:48
【问题描述】:

这是我从微读取数据的功能,但是为什么当我通过调用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;
}

【问题讨论】:

  • 它必须是:char *buf = new char[bufSize]; 而不是 (bufSize)。如果你使用 new,也要使用 delete。

标签: c++ alsa


【解决方案1】:

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

【讨论】:

  • 天哪,这么愚蠢的错误,好久没用c++了,谢谢。
猜你喜欢
  • 2014-10-31
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-05-08
  • 1970-01-01
  • 1970-01-01
  • 2020-02-07
相关资源
最近更新 更多