当我使用 ALSA 库的函数 `snd_pcm_readi` 时它崩溃了
it crash when I use ALSA lib's function `snd_pcm_readi`
这是我从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;
}
new char(bufSize)
分配单个 char
并将其初始化为 bufSize
。你想要new char[bufSize]
。当你 new[]
某些东西时,你必须 delete[]
稍后,而不是 free
它。
char *buf = new char[bufSize];
...
delete[] buf;
为避免必须手动管理内存,您可以使用 std::unique_ptr
或 std::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
这是我从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;
}
new char(bufSize)
分配单个 char
并将其初始化为 bufSize
。你想要new char[bufSize]
。当你 new[]
某些东西时,你必须 delete[]
稍后,而不是 free
它。
char *buf = new char[bufSize];
...
delete[] buf;
为避免必须手动管理内存,您可以使用 std::unique_ptr
或 std::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