我尝试编写从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 ));
但是这样运行之后: 〜#dd if = / dev / zero bs = 1024 count = 8 | ./test 我有这个错误:
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
任何人都可以帮助我。
答案 0 :(得分:3)
inputMsgBufCount
应该递增。你在第一次阅读时就做对了,但对于其他一切,你在重新分配后立即增加它。如果您遵循它的值,则在您进入循环时它为1。您重新分配到2*bufSize
,并增加inputMsgBufCount
,这使其成为2.然后您阅读数据,并将其复制到msg+2*bufSize
。这会破坏你的缓冲区。您应该已复制到msg+bufSize
。只需延迟递增变量,直到复制数据为止。
另一方面,您可以安全地使用memcpy()
复制数据。 msg
和inputBuffer
永远不会重叠。实际上你应该完全摆脱inputBuffer
,并在正确的偏移处直接读到msg
。