我尝试编写从标准输入读取数据的代码:
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 ));
但是运行之后是这样的: ~# dd if=/dev/zero bs=1024 count=8 | ./测试 我有这个错误:
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
谁能帮帮我
最佳答案
inputMsgBufCount
应该在您复制信息缓冲区中的数据后递增。你在第一次读取时就做对了,但对于其他所有内容,你在重新分配后立即增加它。如果你遵循它的值,当你进入循环时它是 1。您重新分配给 2*bufSize
,并增加 inputMsgBufCount
,使其成为 2。然后您读取数据,并将其复制到 msg+2*bufSize
。这正在破坏您的缓冲区。您应该已经复制到 msg+bufSize
。只需延迟递增变量,直到您复制数据。
另一方面,您可以安全地使用memcpy()
来复制数据。 msg
和 inputBuffer
永远不会重叠。实际上,您可能应该完全摆脱 inputBuffer
,并在正确的偏移量处直接读入 msg
。
关于c - 重新分配错误 : incorrect checksum for freed object,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5642941/