2017-08-01 1 views
0

をsnd_pcm_readi`これは私がミクロからデータを読み込む機能があるが、なぜ私は、コールnew、アプリケーションのクラッシュによるバッファを割り当てるとき、私はmallocを使用している場合、それOK私はALSA libにの機能を使用する場合、それは `クラッシュが

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

それでなければならない: 'のchar *のBUF =新しいCHAR [BUFSIZE];' 'ない(BUFSIZE)'。また、newを使用する場合はdeleteを使用してください。 –

答えて

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 
+0

ああ私の神、愚かな間違い、長い時間はC++を使用しない、ありがとう。 – sundq

関連する問題