开发者

realloc error: incorrect checksum for freed object

I try to wrote code that read data from stdin:

size_t bufSize = 1024;
unsigned char *msg = NULL;
size_t msgBytes = 0;
size_t inputMsgBufCount = 0;
unsigned char inputBuffer[bufSize];
size_t bytesRead = 0;
unsigned char *tmp = NULL;

if ((msg = (unsigned char *)malloc(sizeof(unsigned char) * bufSize)) == NULL)
    exit(EXIT_FAILURE);
bytesRead = fread(msg, sizeof(unsigned char) * bufSize, 1, stdin);
inputMsgBufCount++;

while (bytesRead) {
    printf("iteration: %lu\n", inputMsgBufCount);
    if ( (tmp = (unsigned char *)realloc(msg, (inputMsgBufCount * bufSize) + bufSize)) != NULL ) {
         printf("reallocated\n");
        msg = tmp;
        inputMsgBufCount++;
    }
    else {
        printf("Ran out of memory\n");
        free(msg);
    }
    bytesRead = fread(inputBuffer, sizeof(unsigned char) * bufSize, 1, stdin);
    memmove((msg + (inputMsgBufCount * bufSize)), inputBuffer, bufSize);
}

free(msg);

msgBytes = (inputMsgBufCount * bufSize);

gettimeofday(&end, NULL);
printf("%10.6lf [MB/s]\n", (msgBytes / (1<<20)) / ( (end.tv_sec - start.tv_sec) + (end.tv_usec - start.tv_usec) * 1.0e-6f ));

But after run it like this: ~# dd if=/开发者_JS百科dev/zero bs=1024 count=8 | ./test I have this error:

iteration: 1
reallocated
iteration: 2
reallocated
iteration: 3
reallocated
iteration: 4
reallocated
iteration: 5
reallocated
iteration: 6
reallocated
iteration: 7
test(11450) malloc: *** error for object 0x100804008: incorrect checksum for freed object - object was probably modified after being freed.
*** set a breakpoint in malloc_error_break to debug
Abort trap

Can anyone help me please.


inputMsgBufCount is supposed to be incremented after you copy the data in your msg buffer. You do it right on your first read, but for everything else, you increment it immediately after you realloc. If you follow the values for it, it is 1 as you enter the loop. You reallocate to 2*bufSize, and increment inputMsgBufCount, which makes it 2. Then you read the data, and copy it to msg+2*bufSize. This is corrupting your buffer. You should have copied to msg+bufSize. Simply delay incrementing the variable until after you copy your data.

On another note, you can safely use memcpy() to copy data. msg and inputBuffer will never overlap. Actually you should probably get rid of inputBuffer altogether, and read directly into msg at the right offset.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜