views:

66

answers:

2
char *strip_postfix(char *str1, char *str2)
{
   int i;

   for(i=0; str2[i] != '\0'; i++)
   {
      if(str1[i] != str2[i])
      {
         str1[i] = '\0';
         break;
      }
   }
   return str3;
}

This code, is giving segmentation fault error at line str1[i] = '\0' during run time..... I think there is some memory allocation issue,, as while I create a new variable and copy the contents there, and then return that new variable, everything works fine.... Please let me know what's the issue in this.

+4  A: 

What happens if str1 is smaller than str2?

You also have:

return str3;

Which makes me think this code will not compile in its current form...

Gian
If `str1` is smaller than `str2` the `if`-condition in the loop will be true at the end of `str1` and the function will exit without any bad effects.
sth
Except that it segfaults because it's off-by-1.
Gian
Doesn't it just assign `'\0'` to that place in `str1` that already contains this strings terminating `\0`?
sth
A: 

Your code should like

int str1len =  strlen(str1);    
for(i=0; str2[i] != '\0'; i++)
   {
      if(str1[i] != str2[i] || i >= str1len)
      {
         str1[i] = '\0';
         break;
      }
   }
return str1;

Thanks

Muhit
You're missing the declaration of `i`.
Thom Smith
If `str2` is a prefix of `str1` this will not return the common prefix.
sth