C++ 当我使用ALSA lib&\x27时,它崩溃了;s函数'snd_pcm_readi`
这是我从micro读取数据的函数,但是为什么当我通过调用C++ 当我使用ALSA lib&\x27时,它崩溃了;s函数'snd_pcm_readi`,c++,alsa,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);
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;
}
void AlsaMicrophoneWrapper::readThreadFunction()
{
int bufSize=m_比特帧*m_帧;
//char*buf=new char(bufSize);//崩溃
char*buf=(char*)malloc(bufSize);
如果(NULL==buf)
{
printf(“Snd_ReadThread allocate mem error\n”);
返回;
}
snd_pcm_sframes_t retFrame;
ssize_t返回代码;
while(true)
{
retFrame=snd_pcm_readi(m_pcm句柄、buf、m_帧);
如果(-eppe==retFrame)
{
snd_pcm_prepare(m_pcm手柄);
}
否则如果(retFrame>0)
{
returnCode=m_writer->write(buf,retFrame);
如果(returnCodenew char(bufSize)
分配一个char
并将其初始化为bufSize
。您需要new char[bufSize]
。当您new[]
某物时,您必须稍后删除[]
它,而不是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
auto-buf=std::使_唯一(bufSize);
//使用buf.get()访问分配的内存
或
std::vector buf(bufSize);
//使用buf.data()访问分配的内存
newchar(bufSize)
分配一个char
并将其初始化为bufSize
。您需要new char[bufSize]
。当您new[]
某个东西时,您必须稍后删除它,而不是免费的
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
auto-buf=std::使_唯一(bufSize);
//使用buf.get()访问分配的内存
或
std::vector buf(bufSize);
//使用buf.data()访问分配的内存
必须是:char*buf=new char[bufSize];
not(bufSize)
。如果使用new,也可以使用delete。必须是:char*buf=new char[bufSize];
not(bufSize)如果你使用Neo,也使用删除。哦,我的天,这么愚蠢的错误,长时间不用C++,谢谢你。哦,天哪,这么愚蠢的错误,长时间不用C++,谢谢。