이 코드를 컴파일하고 실행할 때 오류가 발생합니다. 오류 메시지는 다음과 같습니다realloc() : 다음 크기가 유효하지 않음 : 0x0000000002119010
이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;
}
'realloc'에서'(char *) realloc (content, sizeof (char) * (++ mem_block_count) * BUF_LEN); – Naveen
realloc 후 컨텐츠가 유효하지 않을 수 있습니다 (realloc에 의해 해제되었을 수 있음). 제 생각에는 ct_head가 아닌 realloc이 반환 한 포인터를 할당해야한다고 생각합니다. – qbert220
[malloc/realloc 함수의 반환 유형을 형 변환하지 마십시오.] (http://stackoverflow.com/a/605858/1151654)주의하십시오. – Eregrith