0

In the following program, p is declared as a pointer(which is constant BUT string is not).But still the program does not work and stops abruptly saying "untitled2.exe has stopped working".

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

int main(){
    char * const p = "hello";
    *p = 'm';
    return 0;
}

Why this unexpected behaviour?

Nikunj Banka
  • 11,117
  • 16
  • 74
  • 112
  • This doesn't even look like it should compile. The first line of `main` is missing a semi-colon, for one. – Gian Jun 17 '13 at 00:58
  • 2
    "hello" is a literal and stored in static memmory, it can not be modified. – Bill Hoo Jun 17 '13 at 01:04
  • 1
    http://stackoverflow.com/questions/890535/what-is-the-difference-between-char-const-and-const-char/890560#890560 remember that, as a rule of the thumb, every time you are using `const` your are triggering some internal actions performed by the compiler. – user2485710 Jun 17 '13 at 10:50

3 Answers3

5

You are getting a Windows error because you are invalidly accessing memory. On other systems you might get a SEGFAULT or SEGV or a Bus error.

*p = 'm';

Is trying to change the first letter of the constant string "hello" from 'h' to 'm';

Old Pro
  • 24,624
  • 7
  • 58
  • 106
5

Albeit p itself is a pointer to a non-const object, it is pointing to a string literal. A string literal is an object which, although not const-qualified with regards to its type, is immutable.

In other words, p is pointing to an object which is not const, but behaves as if it were.

Read more on ANSI/ISO 9899:1990 (C90), section 6.1.4.

alecov
  • 4,882
  • 2
  • 29
  • 55
2
char * const p = "hello";

defines a constant pointer p and initialises it with the memory address of a constant string "hello" which is inherently of type const char *. By this assignment you are discarding a const qualifier. It's valid C, but will lead to undefined behaviour if you don't know what you are doing.

Mind that const char * forbids you to modify the contents of the memory being pointed to, but does not forbid to change the address while char * const permits you to modify the contents, but fixes the address. There is also a combo version const char * const.

Although this is valid C code, depending on your OS placement and restrictions on "hello" it may or may not end up in writable memory. This is left undefined. As a rule on thumb: constant strings are part of the executable program text and are read-only. Thus attempting to write to *p gives you a memory permission error SIGSEGV.

The correct way is to copy the contents of the string to the stack and work there:

char p[] = "hello";

Now you can modify *p because it is located on the stack which is read/write. If you require the same globally then put it into the global scope.

Sergey L.
  • 21,822
  • 5
  • 49
  • 75