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?
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';
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.
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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.