2

In C++11, char pointers cannot be initialized to string literals directly.
In earlier versions of C++, I could do this with no issue.

If the code below is allowed:

char arr[] = "Hello";
char *p_str1 = arr;  //allowed

Then why is the code below not allowed?

char *p_str3 = "Hello"; //Not allowed

Note: I am aware adding const would fix. But I need to know the reasons.

anastaciu
  • 23,467
  • 7
  • 28
  • 53
Sumaiya A
  • 137
  • 1
  • 14

2 Answers2

5

char arr[] = "Hello" stores a modifiable copy of the string literal "Hello" in the char array arr, the p_str1 variable is a pointer to that array, since the data is modifiable the pointer does not need to be const.

char *p_str3 = "Hello" is a pointer directly to a string literal that is read-only. The pointer does not own the string literal, more often than not these are stored in some read-only section of memory, either way you can access the data, but you can't modify it. Making the const pointer obligatory avoids undesired problems at runtime.

The C++ standard does not allow for non-const pointers to unmodifiable data. And that is fortunate because it avoids undefined behavior by way of attempting to modify it, as often happens in C where this rule doesn't exist.

It was still legal to use non-const char pointer in C++03 (perhaps for legacy reasons), when it was deprecated, after C++11 it was disallowed. As far as I can tell attempting to modify these string literals was always undefined behavior.

anastaciu
  • 23,467
  • 7
  • 28
  • 53
2

It's because C++ understands that the string constant will be stored in non-modifiable memory, so it must be flagged as const. In many compilers this is stored in a read-only data segment.

Any attempt to modify that string could result in a segmentation fault.

In the first case you're actually making a copy to a local array. This is modifiable.

tadman
  • 208,517
  • 23
  • 234
  • 262
  • How is the first approach different from approach 2. Need clarity. string constant will not be stored in non-modifiable memory then? – Sumaiya A Apr 06 '21 at 22:57
  • In the first case you're saying "please create a local array that has a copy of the following contents" and on most compilers that's stored on the stack. – tadman Apr 06 '21 at 22:59
  • 3
    *Any attempt to modify that string could result in a segmentation fault.* or worse. I remember the nefarious and mysterious "Bus Error". – user4581301 Apr 06 '21 at 23:07