当我编译并运行这段代码时,我得到一个错误。错误信息是:
realloc(): invalid next size: 0x0000000002119010
该文件input
大约有4000字。
我调试了它,但我找不到任何问题。
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <fcntl.h>
#define BUF_LEN 10 //buf length
int main(int argc, char *argv[])
{
int file_d; //file descriptor
char *ct_head; //content_first_char
char *content;
ssize_t read_len = BUF_LEN; //had read length
int mem_block_count = 0;
file_d = open("input", O_RDONLY);
if (file_d < 0)
{
perror("open");
exit (1);
}
content = ct_head = (char *) malloc(sizeof(char) * BUF_LEN);
mem_block_count = 1;
while (read_len == BUF_LEN)
{
read_len = read(file_d, ct_head, BUF_LEN);
if (read_len < 0)
{
perror("read");
exit(2);
}
if (read_len == BUF_LEN)
{
ct_head = (char *)realloc(content, sizeof(char) *(++mem_block_count));
ct_head = &content[(mem_block_count-1) * BUF_LEN];
}
else
ct_head[read_len] = '\0';
}
printf("%s", content);
close(file_d);
free(content);
return 0;
}