0

Possible Duplicate:
Why do I get a segmentation fault when writing to a string?

I was writing a simple string function. The problem is: I declare a char pointer, then once I try to update a specific character, the program crashes.

I have checked some previously written string processing, I found that they modify specific characters. But when I try to run them, I get the same problem.

Sample:

   stringprocess()
{
 char *s;
 s=" I am c programmer";
 s=" but, ..... um";

 *s='x'; //program crashes here...

 *p="abc";
 *s=*p; // this also cause crashing
........
}  

Why does this happen?

Community
  • 1
  • 1

1 Answers1

4
s=" but, ..... um";

s points to a string literal. Trying to modify a string literal invokes undefined behaviour. Often, string literals are stored in read-only memory, then a crash is the immediate consequence of such an attempt.

You should use a char s[100] (just for example) or a malloced pointer if you want to modify the contents.

Daniel Fischer
  • 181,706
  • 17
  • 308
  • 431