的char *的printf的获取分割故障 [英] printf of char* gets Segmentation Fault
问题描述
我想从套接字和打印读取用printf(必须的),到标准输出;
I'm Trying to read from a socket and print to stdout using printf (a must);
不过,我得到一个分段错误每次我读了理智网站上的特定文件(HTML)的时间。
However I get a Segmentation Fault every time I read a specific file (an HTML) from the sane web site.
请,看看这个code和告诉我什么是错误的。
Please, take a look at this code and tell me what wrong.
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
无法找到进一步的参数。
response_data
is probably not NUL ('\0'
) terminated, so printf
continues past the end of the string. Or possibly it contains a %
directive but printf
can't find further arguments.
相反,告诉的printf
多远阅读,的不的国米preT任何%
字符串中的指令。
Instead, tell printf
how far to read, and not to interpret any %
directives in the string.
printf("%.*s", total_read, response_data);
请注意,如果 RESPONSE_DATA
包含一个内嵌的NULL,的printf
将停在那里,即使 total_read
是更长的时间。
Note that if response_data
contains an embedded NUL, printf
will stop there even if total_read
is longer.
这篇关于的char *的printf的获取分割故障的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!