我尝试编写从标准输入读取数据的代码:
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 我有这个错误:
迭代:1 重新分配 迭代:2 重新分配 迭代:3 重新分配 迭代次数:4 重新分配 迭代次数:5 重新分配 迭代:6 重新分配 迭代次数:7 test(11450) malloc: *** 对象 0x100804008 错误:已释放对象的校验和不正确 - 对象在被释放后可能已被修改。 *** 在 malloc_error_break 中设置断点进行调试 中止陷阱
谁能帮助我。