Windows 7, 64bit, MinGW toolset, following code:
m_data = reinterpret_cast<SampleType *>(realloc(m_data, m_size + v));
if (NULL == m_data){
perror ("realloc failed");
exit(-1);
}
fails with the message realloc failed: Not enough space
It happens even if I asked 100 bytes more. And no matter whether I use malloc (with the correspondind pointer reaasignment) or realloc. I always get the same.
The computer reports over 1GB available free memory.
Above is fragment of the method. Below is its entire code.
The point is that this method allocates memory first time when this method has m_data equal to NULL and enlarges it in cosenquent calls. So, pls, see below
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;
};
So, in first time a memory is allocated using malloc. Don’t doubt.
Debugger session trace.
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]
The root of cause of the error was stack destruction happened due to mess in memory addressing in memory management functions. For example, in the following code line
m_data + m_sizemeans not what it was intended becausem_datapoints to a two byte size type whilem_sizeis size in bytes. Som_data + m_sizeoffsets poninter not to the end ofm_databut on to the distance twice far.