为什么下面的代码会出现分段错误问

时间:2011-06-19 11:53:17

标签: c segmentation-fault

  

可能重复:
  Why does simple C code receive segmentation fault?

我有下面的代码将从字符串中删除尾随空格但我不知道 进入这段代码,因为它给出了分段错误问题??

 void main(void);

char* rtrim(char*);

void main(void)
 { 
 char* trail_str = "This string has trailing spaces in it.               ";


 printf("Before calling rtrim(), trail_str is '%s'\n", trail_str);

 printf("and has a length of %d.\n", strlen(trail_str));



 rtrim(trail_str);



 printf("After calling rtrim(), trail_str is '%s'\n", trail_str);

 printf("and has a length of %d.\n", strlen(trail_str));

 }


  char* rtrim(char* str)
  {
   int n = strlen(str) - 1;    

    while (n>0)            
   {
       if (*(str+n) != ' ')    
      {

           *(str+n+1) = '\0'; 



           break;             
      }

      else

      n--;
 }

 return str;      

 }

2 个答案:

答案 0 :(得分:3)

trail_str指向内存中的常量区域,因此无法在*(str+n+1) = '\0'

中更改 初始化时

char* trail_str = "This string has trailing spaces in it.               ";

你实际生成一个常量字符串:"This string has trailing spaces in it. "并告诉trail_str指向它。

答案 1 :(得分:2)

char* trail_str = "This string has trailing spaces in it.               ";

tail_str指向的字符串可以存储在只读内存中。你不能修改它。

如果要修改它,则需要为其分配存储空间并将该字符串复制为常量。

(另外,main应该返回int,而不是void。)