2

Possible Duplicate:
C/C++ Char Pointer Crash

char *p = "atl";
char c;
c = ++*p; //crashing here

Why it is crashing?

I know the memory is not created for pointer increment should have be done on data.

Community
  • 1
  • 1
Suri
  • 3,287
  • 9
  • 45
  • 75
  • This question has been asked many, many times before: http://stackoverflow.com/questions/4226829/c-c-char-pointer-crash http://stackoverflow.com/questions/2437318/why-does-this-code-crash http://stackoverflow.com/questions/5972915/string-constants-vs-char-arrays-in-c http://stackoverflow.com/questions/5142988/c-pointer-arithmetic-on-characters http://stackoverflow.com/questions/3090610/c-char-pointer-problem just to name a few – Adam Rosenfield Jul 16 '11 at 04:22

1 Answers1

8

p points to const data which is the string literal "atl"; that means, *p cannot be changed. But you're trying to change it by writing ++*p. That is why its crashing at runtime.

In fact, most compilers would give warning when you write char *p ="atl". You should write:

const char *p ="atl";

If you write so, then the compiler would give error when you write ++*p at compilation time itself. Detection of error at compile time is better than detection of error at runtime. See the compilation error here now:

The compilation error is:

prog.cpp:7: error: increment of read-only location ‘* p’


However, if you write

 char p[] = "atl";
 char c = ++*p;  //ok

then its correct now. Because now p is an array which is created out of the string literal "atl". It doesn't point to the string literal itself anymore. So you can change the content of the array.

Nawaz
  • 353,942
  • 115
  • 666
  • 851
  • char str1[] = {'s', 'o','m','e'}; char str2[] = {'s','o','m','e','\0'}; char *p = str1; char c = ++*p; is above program different ?(it is not crashing) – Suri Jul 16 '11 at 04:23
  • 1
    thanks i understood the point – Suri Jul 16 '11 at 04:28