2016-02-27 49 views
0

我是C新手,第二次調用函數時出現意外值。C - 調試內存問題

我不明白爲什麼會發生這種情況,因爲我正在爲methodtargetversion分配新內存。

first run: 
GET/HTTP/1.1 
method: 'GET', target: '/', version: 'HTTP/1.1' 

second run: 
GET/HTTP/1.1 
method: 'GET�1', target: '/�1', version: 'HTTP/1.1��1' 

代碼:

bool parse(const char* line, char* abs_path, char* query) 
{ 
    char* method = malloc(LimitRequestLine + 1); 
    char* target = malloc(LimitRequestLine + 1); 
    char* version = malloc(LimitRequestLine + 1); 

    // iterate over chars from line and set method, target and version respectively 
    for (int i = 0, j = 0, part = 0, n = strlen(line); i < n; i++) { 
     if (line[i] == ' ') { 
      part++; 
      j = 0; 
      continue; 
     } else if (line[i] == '\r' || line[i] == '\n') { 
      break; 
     } 
     if (part == 0) 
       method[j] = line[i]; 
     else if (part == 1) 
       target[j] = line[i]; 
     else if (part == 2) 
       version[j] = line[i]; 
     j++; 
    } 
    printf("method: '%s', target: '%s', version: '%s'\n", method, target, version); 

    ... 

} 

是不是有什麼毛病我分配和寫入到這裏該內存這可以解釋這些多餘的字符是如何追加的方式?

回答

2

您必須通過添加空字符來終止字符串。

在這種情況下,使用calloc()是一種簡單的方法。

char* method = malloc(LimitRequestLine + 1); 
char* target = malloc(LimitRequestLine + 1); 
char* version = malloc(LimitRequestLine + 1); 

應該是

char* method = calloc(LimitRequestLine + 1, sizeof(char)); 
char* target = calloc(LimitRequestLine + 1, sizeof(char)); 
char* version = calloc(LimitRequestLine + 1, sizeof(char)); 
+0

或'memset的(方法,0,LimitRequestLine + 1)'等...每個'malloc'後 - 相同的原理。不得不承認,從未想過使用'calloc'作爲替代方案。 – isedev

+0

'calloc()'會將所有分配的字節初始化爲0,這是不必要的,使程序變慢。 –

+0

太棒了,讓它工作。非常感謝! – Subbeh