2010-12-05 66 views
0

我试图从套接字读取并使用printf(必须)打印到标准输出;char * 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); 

谢谢。

+1

您应该通过解决您的问题的答案点击对勾形图标。 – erjiang 2010-12-05 20:55:19

+1

什么可能在response_data中?如果它包含printf格式的字符,printf将尝试访问一些你没有通过的参数。试试看呢? – 2010-12-05 20:55:55

回答

9

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

取而代之的是告诉printf要读多远,而不是来解释字符串中的任何%指令。

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

注意,如果response_data包含一个内嵌的NULL,printf将停在那里,即使total_read更长。

+1

一个更正是:printf(“%。* s”,total_read,response_data); (在星号之前不要)。 – 2010-12-06 01:04:42

+0

@Luis:只有`response_data`有一个内嵌的NULL,其中`%* s`垫用空格,`%事项 - * s`垫与另一侧的空间,而`%* s`确实没有填充在所有。取决于OP想要的内容... – ephemient 2010-12-06 01:11:08

1

什么可能在response_data?如果它包含printf格式字符(即%后跟其中一个常用选项),则printf将尝试访问一些未通过的参数,并且很可能出现分段错误。试试puts而不是?

如果必须用printf,做printf("%s", response_data)(和第一NUL,终止它)从你的帖子,响应是HTML数据

-2

我的理解。
而且由于它是文本,您尝试打印它。不要像你那样使用printf。
而是做到以下几点:

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