2010-12-05 64 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);