The code below attempts to save a data stream to a file using fwrite. The first example using malloc works but with the second example the data stream is %70 corrupted. Can someone explain to me why the second example is corrupted and how I can remedy it?
short int fwBuffer[1000000];
// short int *fwBuffer[1000000];
unsigned long fwSize[1000000];
// Not Working *********
if (dataFlow) {
size = sizeof(short int)*length*inchannels;
short int tmpbuffer[length*inchannels];
int count = 0;
for (count = 0; count < length*inchannels; count++)
{
tmpbuffer[count] = (short int) (inbuffer[count]);
}
memcpy(&fwBuffer[saveBufferCount], tmpbuffer, sizeof(tmpbuffer));
fwSize[saveBufferCount] = size;
saveBufferCount++;
totalSize += size;
}
// Working ***********
if (dataFlow) {
size = sizeof(short int)*length*inchannels;
short int *tmpbuffer = (short int*)malloc(size);
int count = 0;
for (count = 0; count < length*inchannels; count++)
{
tmpbuffer[count] = (short int) (inbuffer[count]);
}
fwBuffer[saveBufferCount] = tmpbuffer;
fwSize[saveBufferCount] = size;
saveBufferCount++;
totalSize += size;
}
// Write to file ***********
for (int i = 0; i < saveBufferCount; i++) {
if (isRecording && outFile != NULL) {
// fwrite(fwBuffer[i], 1, fwSize[i],outFile);
fwrite(&fwBuffer[i], 1, fwSize[i],outFile);
if (fwBuffer[i] != NULL) {
// free(fwBuffer[i]);
}
fwBuffer[i] = NULL;
}
}
You initialize your
sizeasthen you declare an array of size
This is already highly suspect. Why did you include
sizeof(short int)into the size and then declare an array ofshort intelements with that size? The byte size of your array in this case isi.e. the
sizeof(short int)is factored in twice.Later you initialize only
length * inchannelselements of the array, which is not entire array, for the reasons described above. But thememcpythat follows still copies the entire array(Tail portion of the copied data is garbage). I’d suspect that you are copying
sizeof(short int)times more data than was intended. The recipient memory overflows and gets corrupted.The version based on
mallocdoes not suffer from this problem sincemalloc-ed memory size is specified in bytes, not inshort int-s.If you want to simulate the
mallocbehavior in the upper version of the code, you need to declare yourtmpbufferas an array ofcharelements, not ofshort intelements.