printf of char* gets Segmentation Fault

2019-09-02 09:27发布

问题:

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.

回答1:

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.

Instead, tell printf how far to read, and not to interpret any % directives in the string.

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

Note that if response_data contains an embedded NUL, printf will stop there even if total_read is longer.



回答2:

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. Try puts instead?

If you must use printf, do printf("%s", response_data) (and NUL-terminate it first)



回答3:

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:

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