2012-11-28 54 views
2

Valgrind的輸出 「尺寸1的無效讀」:Valgrind的錯誤:由於的strstr()以C

GET /cs3157/tng/index.html 
==760== Invalid read of size 1 
==760== at 0x4C2E7D4: strstr (in /usr/lib/valgrind/vgpreload_memcheck-amd64-linux.so) 
==760== by 0x400E67: HandleTCPClient (http-server.c:101) 
==760== by 0x400D42: main (http-server.c:75) 
==760== Address 0x0 is not stack'd, malloc'd or (recently) free'd 

相關的代碼:

FILE *input = fdopen(clntSocket, "r");  //socket wrapped with FILE * 
if (input == NULL) 
{ 
    perror("fdopen failed"); 
    fclose(input); 
    return; 
} 
char request_buffer[100]; 
char out_buf[BUF_SIZE]; 
int len, res; 

while(fgets(request_buffer, sizeof(request_buffer),input) != NULL) 
{ 
    request_buffer[sizeof(request_buffer)-1] = '\0'; //null terminates buffer 
    char *request = request_buffer; 
    char *token_separators = "\t \r\n"; // tab, space, new line 
    char *method = strtok(request, token_separators); 
    char *requestURI = strtok(NULL, token_separators); 
    char *httpVersion = strtok(NULL, token_separators); 

    if(strstr(method,"GET") != NULL) 
    { 
      if(requestURI[strlen(requestURI)] == '/') 
        requestURI = strcat(requestURI,"index.html"); 
      printf("%s %s\n", method, requestURI); 

    } 
    memset(request_buffer,'\0',sizeof(request_buffer)); 
} 

fclose(input);  //close the socket by closing the FILE * wrapper 

我讀到此錯誤通常是由故障引起的以null終止字符串。我認爲在fgets()之後的第一行會阻止它成爲問題。我在猜測我忽略了一些東西。我感謝任何幫助。

編輯:程序結束與分段故障崩潰。

回答

2

聽起來(來自Valgrind的報告),好像methodNULL。您應該使用調試器逐步執行此代碼,以驗證令牌化是否按預期工作。

此外,您應該聲明所有這些指針爲const char *,因爲它們不打算寫入。這當然是一個小問題,但我會盡可能鼓勵使用const。 :)

+0

情況就是這樣。我在strstr()調用之前添加了if(method!= NULL && requestURI!= NULL && httpVersion!= NULL)並且能夠避免該錯誤。謝謝! –

+0

@Twigger好的,很好。我真的認爲這是你應該接受的答案,然後,因爲我在peterph之前回答(正確)。 :) – unwind

+0

從我的角度來看,我正在學校的服務器上工作,並且沒有辦法通過調試程序來執行代碼,而沒有很大的不便。 Peterph的答案更容易應用,並幫助我首先進行連接。 –

1
Address 0x0 is not stack'd, malloc'd or (recently) free'd 

這裏有些不對勁:該程序似乎是取消引用NULL。我想知道最終是否會出現段錯誤 - 您應該檢查strtok()的返回值,因爲如果沒有找到更多的標記,它將返回NULL。

+0

存在分段錯誤。我編輯了這篇文章。 –

+0

在strstr()調用之前添加if(method!= NULL && requestURI!= NULL && httpVersion!= NULL)之後,我能夠避免該錯誤。謝謝! –