2011-07-11 141 views
0

下面的代碼是隨機segfaulting,我似乎無法看到它是什麼問題。任何幫助,將不勝感激。我使用gdb和核心文件將它隔離爲這個函數。我得到一個段錯誤,似乎無法找到它

char* chomp(char *str) 
{ 
    unsigned int scan_ind, curr_ind; 

    scan_ind = curr_ind = 0; 

    while(str[scan_ind]) 
    { 
     if(str[scan_ind] != 0x0A && 
     str[scan_ind] != 0x0D) 
     { 
     if(curr_ind != scan_ind) 
      str[curr_ind] = str[scan_ind]; 

     curr_ind++; 
     } 

     scan_ind++; 
    } 

    str[curr_ind] = 0; 

    return str; 
} 
+1

是否給它一個零終止的字符串? –

+1

你試過通過valgrind運行它時,它segfaults? – houbysoft

回答

4

該代碼看起來沒問題,至少乍一看。一種可能性是,如果您傳遞的字符串不是以null結尾,或者是不可修改的(例如字符串文字)。

對於它的價值,你的函數可以被簡化了不少,喜歡的東西:

char *chomp (char *str) { 
    char *from = str;       // This is the pointer for reading. 
    char *to = str;       // This is the pointer for writing. 

    while (*from != '\0') {     // Until end of string. 
     if((*from != '\n') && (*from != '\r')) // Transfer desired characters only. 
      *to++ = *from;      // Only increase write pointer if transferred. 
     from++;         // Increase read pointer no matter what. 
    *to = '\0';        // Truncate string if necessary. 
    return str;        // And return the in-situ modified string. 
} 

這不會幫助您與非空終止字符串或字符串文字,但它是一個有點短,更像C。

+0

null('str [scan_ind])' – lccarrasco

+0

中隱式檢查了空終止符,而(str [scan_ind])則隱式檢查空終止符,直到找到該字符串的結尾爲止。 –

+0

這是一個很好的做法,只測試條件內的布爾值。即使來自!='\ 0'的'*最有可能產生與'* from'相同的機器碼,前者清楚地表明正在測試字符串結束字符的指針字符。始終選擇可讀性,特別是在沒有運行時成本的情況下。 –

2

難道你的輸入是一個字符串文字(如chomp(「胡蘿蔔」))或一個字符串文字的指針?在這種情況下,函數將失敗,因爲字符串文字是隻讀的,並且您寫入它。

如果您使用字符串文字作爲此函數的輸入,請嘗試將其複製到緩衝區中,然後調用該函數。更好的是,如果可能的話,重新構造該函數,以便將str立即複製到動態分配的緩衝區中,然後在該函數的其餘部分中使用該緩衝區,並將其返回。

+0

這很可能是問題所在。他可能試圖寫入只讀內存。 – atx

相關問題