Why below code gives segmentation fault problem? [duplicate]
Possible Duplicate:
Why does simple C code receive segmentation fault?
I have code below which will remove trailing spaces from a string but i don't what going in this code so as it gives segmentation fault problem??
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开发者_JS百科("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;
}
trail_str points to a constant area in the memory and thus cannot be changed in *(str+n+1) = '\0'
when initializing
char* trail_str = "This string has trailing spaces in it. ";
you actualy generate a constant string: "This string has trailing spaces in it. "
and tell trail_str
to point to it.
char* trail_str = "This string has trailing spaces in it. ";
The string pointed to by tail_str
can be stored in read-only memory. You can't modify it.
If you want to modify it, you'll need to allocate storage for it and copy that string constant .
(Also, main
should return an int
, not void
.)
精彩评论