char* 的 printf 出现分段错误
我正在尝试从套接字读取并使用 printf 打印到标准输出(必须);
然而,每次我从正常的网站读取特定文件(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);
谢谢。
I'm Trying to read from a socket and print to stdout using printf (a must);
However I get a Segmentation Fault every time I read a specific file (an HTML) from the sane web site.
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);
Thank You.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
response_data
可能不是 NUL ('\0'
) 终止,因此printf
会继续到字符串末尾。或者它可能包含%
指令,但printf
无法找到更多参数。相反,告诉
printf
读取多远,并且不解释字符串中的任何%
指令。请注意,如果
response_data
包含嵌入的 NUL,即使total_read
更长,printf
也会在那里停止。response_data
is probably not NUL ('\0'
) terminated, soprintf
continues past the end of the string. Or possibly it contains a%
directive butprintf
can't find further arguments.Instead, tell
printf
how far to read, and not to interpret any%
directives in the string.Note that if
response_data
contains an embedded NUL,printf
will stop there even iftotal_read
is longer.response_data
中可能包含什么?如果它包含 printf 格式字符(即%
后跟常用选项之一),printf
将尝试访问一些您未传递的参数,并出现分段错误很有可能。尝试使用puts
来代替?如果必须使用 printf,请执行
printf("%s", response_data)
(并首先以 NUL 终止)What's likely to be in
response_data
? If it contains printf-formatting characters (i.e.%
followed by one of the usual options),printf
will try to access some parameters you've not passed, and a segmentation fault is quite likely. Tryputs
instead?If you must use printf, do
printf("%s", response_data)
(and NUL-terminate it first)我从您的帖子中了解到,响应是 HTML 数据。
由于它是文本,因此您尝试打印它。不要像您那样使用 printf。
相反,请执行以下操作:
My understanding from your post is that the response is the HTML data.
And since it is text you attempt to print it. Do not use printf the way you do.
Instead do the following: