1

i was reading some topics when i found this code and the first comment says

stored in a read-only memory area

What does that mean ?how do i know if the string or variable is read-only ?

char *p = "wikipedia"; // stored in a read-only memory area valid C, deprecated in C++98/C++03, ill-formed as of C++11
p[0] = 'W'; // undefined behavior
Atrox
  • 107
  • 1
  • 6
  • 3
    There's no way to know. You should declare `const char *p` if it will only be used to point to the literal. – Barmar Jul 28 '21 at 16:08
  • The [C11 Standard 6.4.5p7](http://port70.net/~nsz/c/c11/n1570.html#6.4.5) says: "*... If the program attempts to modify such an array, the behavior is undefined.*" It's not *read-only* per se, it's a mnemonic for human programmers; on some implementation it may be modifiable... and, **for that implementation** the behaviour is no longer undefined (provided the feature is documented). – pmg Jul 28 '21 at 16:09

2 Answers2

0

The string "wikipedia" is read-only because it is a literal constant declared in your code.

*p is a pointer, and the memory it is pointing to contains your string "wikipedia". Because that memory is allocated using the apparently deprecated method of assigning a string directly to a pointer, it is read-only.

If you want it to be not read-only, allocate the memory on the stack or the heap. (For example, by using malloc)

izzy
  • 769
  • 2
  • 12
  • 22
  • 1
    "Deprecated" refers to assigning a string literal to a *non-`const`* pointer. `char const *p = "bla";` would be perfectly fine. – Quentin Jul 28 '21 at 16:11
  • 1
    "Deprecated" is also referring to C++ standards only. – Ian Abbott Jul 28 '21 at 16:14
  • but i think if i allocate a pointer in heap using malloc i can read and write from it for example : `char *str = malloc(5*sizeof(char)); str[0] = 'x';` ? – Atrox Jul 28 '21 at 16:25
  • should i learn assembly to understand this low level stuff ? – Atrox Jul 28 '21 at 16:35
0

"wikipedia" it is called the string literal. It does not have to be stored in read-only memory. Standard says that string literals cannot be modified, and if you try to modify one invokes Undefined Behaviour.

char *p = "Wikipedia";

defines pointer p which holds the reference (address) of the string literal "Wikipedia".

If you want to modify that string you need to define a char array:

char p[] = "Wikipedia";
0___________
  • 60,014
  • 4
  • 34
  • 74