char *的printf获取Segmentation Fault

时间:2010-12-05 20:52:25

标签: c segmentation-fault printf

我正在尝试从套接字读取并使用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);

谢谢。

3 个答案:

答案 0 :(得分:9)

response_data可能不是NUL('\0')终止,因此printf继续超过字符串的结尾。或者它可能包含%指令,但printf找不到更多参数。

相反,告诉printf读取多远,来解释字符串中的任何%指令。

printf("%.*s", total_read, response_data);

请注意,如果response_data包含嵌入的NUL,即使printf更长,total_read也会停在那里。

答案 1 :(得分:1)

response_data可能会有什么?如果它包含printf格式化字符(即%后跟一个常用选项),printf将尝试访问您未传递的某些参数,并且很可能出现分段错误。请尝试puts

如果必须使用printf,请执行printf("%s", response_data)(并首先终止NUL)

答案 2 :(得分:-2)

我的理解是,回复是HTML数据 因为它是文本,你试图打印它。不要像你那样使用printf 而是执行以下操作:

for(int i = 0; i < total_read; i++)
   putc(response_data[i],stdout);