2011-07-11 61 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

相关问题