Windows 7、64 位、MinGW 工具集,以下代码:
m_data = reinterpret_cast<SampleType *>(realloc(m_data, m_size + v));
if (NULL == m_data){
perror ("realloc failed");
exit(-1);
}
失败并显示消息realloc failed: Not enough space
即使我再询问 100 个字节,它也会发生。而且无论我是使用 malloc(带有相应的指针重新分配)还是 realloc。我总是一样。
计算机报告超过 1GB 的可用内存。
以上是该方法的片段。下面是它的完整代码。关键是,当方法的 m_data 等于
时,此方法第一次分配内存,并在后续调用中扩大它。所以,请看下面 this
NULL
Wave & operator+= (const Wave wave){
if (NULL != m_data){
m_data = reinterpret_cast<SampleType *>(realloc(m_data, m_size + wave.DataSize()));
if (NULL == m_data){
perror ("realloc failed");
exit(-1);
}
} else {
m_data = reinterpret_cast<SampleType *>(malloc(wave.DataSize()));
m_size = 0; // just for sure
}
/* this code fragment I used instead of realloc's one to prove that realloc is not a root of error cause
SampleType *t_buf = reinterpret_cast<SampleType *>(malloc(m_size + wave.DataSize()));
if (!t_buf) {perror ("malloc failed"); exit(-1);}
memcpy (t_buf, m_data, m_size);
free (m_data);
m_data = t_buf;
*/
memcpy (m_data + m_size, wave.SampleBuffer(), wave.DataSize());
m_size += wave.DataSize();
return *this;
};
因此,第一次使用 malloc 分配内存。不要怀疑。
调试器会话跟踪。
Breakpoint 2, _fu17___ZSt4cout () at ../sound_windows/Sound.h:192
192 if (NULL != m_data){
(gdb) print *this
$2 = {static CHANNEL_NUMBER = <optimized out>, m_format = {wFormatTag = 1, nChannels = 2,nSamplesPerSec = 44100, nAvgBytesPerSec = 176400, nBlockAlign = 4,
wBitsPerSample = 16, cbSize = 18}, m_duration = 0, m_data = 0x0, m_size = 0}
(gdb) cont
Continuing.
Breakpoint 2, _fu17___ZSt4cout () at ../sound_windows/Sound.h:192
192 if (NULL != m_data){
(gdb) print *this
$3 = {static CHANNEL_NUMBER = <optimized out>, m_format = {wFormatTag = 1, nChannels = 2,nSamplesPerSec = 44100, nAvgBytesPerSec = 176400, nBlockAlign = 4,
wBitsPerSample = 16, cbSize = 18}, m_duration = 0.00451559993, m_data = 0x75d9e0, m_size = 800}
(gdb) cont
Continuing.
tried to allocate 800+100 bytes
realloc failed: Not enough space
[Inferior 1 (process 6132) exited with code 037777777777]