-2

下面的代码尝试使用 fwrite 将数据流保存到文件中。使用 malloc 的第一个示例有效,但在第二个示例中,数据流已损坏 %70。有人可以向我解释为什么第二个示例已损坏以及我该如何补救?

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;
        }
    }       
4

2 回答 2

1

This has very good chances to crash

short int tmpbuffer[(short int)(size)];

first size could be too big, but then truncating it and having whatever size results of that is probably not what you want.

Edit: Try to write the whole code without a single cast. Only then the compiler has a chance to tell you if there is something wrong.

于 2012-06-07T15:23:53.500 回答
1

你初始化你size

size = sizeof(short int) * length * inchannels;

然后你声明一个大小数组

short int tmpbuffer[size];

这已经很可疑了。为什么要包含在大小中,然后声明具有该大小的元素sizeof(short int)数组?short int在这种情况下,数组的字节大小是

sizeof(short int) * sizeof(short int) * length * inchannels

即被sizeof(short int)计算了两次。

length * inchannels由于上述原因,稍后您只初始化数组的元素,而不是整个数组。但是memcpy接下来的仍然复制整个数组

memcpy(&fwBuffer[saveBufferCount], &tmpbuffer, sizeof (tmpbuffer));

(复制数据的尾部是垃圾)。我怀疑您复制sizeof(short int)的数据比预期的要多。收件人内存溢出并损坏。

基于的版本malloc不会遇到这个问题,因为malloc-ed 内存大小是用字节指定的,而不是short int-s。

如果要模拟malloc上层代码中的行为,则需要将 your 声明tmpbuffer为元素数组char,而不是short int元素数组。

于 2012-06-07T15:31:15.703 回答