[英]printf of char* gets 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);
谢谢。
response_data
可能不是以NUL( '\\0'
)结尾的,所以printf
继续超过字符串的末尾。 或者它可能包含%
指令,但printf
找不到其他参数。
而是告诉printf
读取的距离,而不要解释字符串中的任何%
指令。
printf("%.*s", total_read, response_data);
请注意,如果response_data
包含嵌入式NUL,则即使total_read
更长, printf
也会在那里停止。
response_data
可能是什么? 如果它包含printf格式的字符(即, %
后接通常的选项之一),则printf
将尝试访问一些尚未传递的参数,并且很可能出现分段错误。 尝试puts
吗?
如果必须使用printf,请执行printf("%s", response_data)
(并先用NUL终止)
根据您的帖子,我的理解是响应是HTML数据。
由于是文本,因此您尝试打印它。 不要像以前那样使用printf。
而是执行以下操作:
for(int i = 0; i < total_read; i++)
putc(response_data[i],stdout);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.