C – Why Program Gives Segmentation Fault

c++pointerssegmentation-faultstring

It's a beginners question: Why is this breaking/giving an error?

#include <stdio.h>    
#include <stdlib.h> 
#include <string.h>

char *strtrim_right(char *p)
{
  char *end;
  int len;
  len = strlen( p);
  while (*p && len)
    {
    end = p + len-1;
    if(isalpha(*end))
     *end =0;
   else 
    break;      
    }
  return(p);
}


int main ()  
{  
  char *x="PM123BFD";
  strtrim_right(x);
  printf("%s", x);
  return 0;
}  

Best Answer

Change

char *x="PM123BFD";

to

char x[]="PM123BFD";

You cannot modify a string literal, so instead pass the function a char array which it can modify.

Related Question