Sna*_*gon 0 c printf segmentation-fault
我正在尝试从套接字读取并使用printf打印到stdout(必须);
但是,每当我从理智的网站上读取特定文件(HTML)时,我都会收到分段错误.
请看一下这段代码并告诉我有什么不对.
int total_read = 0;
char* read_buff = malloc(BUF_SIZE);
char* response_data = NULL;
if (read_buff == NULL){
perror("malloc");
exit(1);
}
while((nbytes = read(fd, read_buff, BUF_SIZE)) > 0){
int former_total = total_read;
total_read += nbytes;
response_data = realloc(response_data, total_read);
memmove(response_data + former_total, read_buff, nbytes); //start writing at the end of spot before the increase.
}
if (nbytes < 0){
perror("read");
exit(1);
}
printf(response_data);
Run Code Online (Sandbox Code Playgroud)
谢谢.
response_data可能不是NUL('\0')终止,所以printf继续超过字符串的结尾.或者它可能包含%指令但printf无法找到更多参数.
相反,告诉printf读取多远,而不是解释%字符串中的任何指令.
printf("%.*s", total_read, response_data);
Run Code Online (Sandbox Code Playgroud)
请注意,如果response_data包含嵌入的NUL,printf即使total_read更长时间也会停在那里.