2017-07-19 53 views
0

我想標記一個字符串,並插入一個標記作爲鍵和其餘作爲地圖的值。但是在插入時,我會遇到分段錯誤。我調試了很長時間,但找不到解決此錯誤的方法。這裏是我的代碼:令牌化字符串時的分段錯誤

while (!fin.eof()) 
{ 
    char *str1; 
    char buf[MAX_CHARS_PER_LINE]; 
    fin.getline(buf, MAX_CHARS_PER_LINE); 
    str1 = new char[strlen(buf)]; 
    int n = 0; 
    char *token[MAX_TOKENS_PER_LINE] = {}; 

    token[0] = strtok(buf, DELIMITER); 

    if (token[0]) 
    { 
     for (n = 1; n < MAX_TOKENS_PER_LINE; n++) 
     { 
      token[n] = strtok(0, DELIMITER); 
      if (!token[n]) break; 
     } 
    } 

    // Forming str1 using the tokens here 
    strcpy(str1, token[0]); 
    strcat(str1, ":"); 
    strcat(str1, token[1]); 
    int key = atoi(token[3]); 

    // Adding str1 to map 
    nameId[key] = str1; 
    } 
} 

任何幫助將不勝感激!

+1

''而只能在心碎結束(fin.eof()!)。測試讀取是否失敗,而不是讀取之前,因此您不處理錯誤的數據。 https://stackoverflow.com/questions/5605125/why-is-iostreameof-inside-a-loop-condition-considered-wrong –

+0

爲什麼你不使用'std :: string',或者至少,存儲' std :: string'在地圖中? – PaulMcKenzie

回答

1

經過進一步調試,我找出了確切的問題。在將它們與str1連接之前,我沒有檢查這些標記是否爲NULL。在我執行該檢查之後,str1總是獲得一個有效值,並因此插入到地圖中。

這是我更新的代碼:

while (!fin.eof()) 
{ 
    char *str1; 
    char buf[MAX_CHARS_PER_LINE]; 
    fin.getline(buf, MAX_CHARS_PER_LINE); 
    str1 = new char[strlen(buf)]; 
    int n = 0; 
    char *token[MAX_TOKENS_PER_LINE] = {}; 

    // Enforcing NULL check for buf 
    if (buf) 
    { 
     token[0] = strtok(buf, DELIMITER); 
    } 

    // Enforcing the NULL check for the tokens 
    if (token[0]) 
    { 
     for (n = 1; n < MAX_TOKENS_PER_LINE; n++) 
     { 
      token[n] = strtok(0, DELIMITER); 
      if (!token[n]) break; 
     } 

     pair<map<int, char *>::iterator, bool> result; 

     // Forming str1 using the tokens here 
     strcpy(str1, token[0]); 
     strcat(str1, ":"); 
     strcat(str1, token[1]); 

     // Adding str1 to map 
     int key = atoi(token[3]); 
     nameId[key] = str1; 
    } 
} 
+1

現在,你所要做的就是找出[爲什麼'while(fin.feof())'總是一個bug](https://stackoverflow.com/questions/5605125/why-is-iostreameof-inside-一個循環條件考慮的,是錯誤的)。 –