0
char* str ="Hello"; 

In the above code the literal "Hello" is stored ... in the DATA segment and it is read-only. So isn't it better to always declare it:

const char* str = "Hello"; 

to avoid improper code such as:

*(str+1) = 't'; 
5
  • 2
    You'll get at least warning in newer versions of compilers for the first syntax. Commented Sep 6, 2019 at 8:16
  • The data segment is not read-only, so on a system with read-only memory segments, it may not be stored there. Commented Sep 6, 2019 at 8:20
  • BTW, no-one really writes *(str+1), except people who do not realize that str[1] is a pointer operation not an array one. Commented Sep 6, 2019 at 8:45
  • @nabroyan: Neither Clang nor GCC for x86_64 give such a warning, even with -Wall. In fact, none of the compilers on Godbolt give such a warning except for AVR gcc. Are you think of C++? Commented Sep 6, 2019 at 11:46
  • @EricPostpischil: Yes, my comment relates to C++. Either I was not attentive to tags or C++ was removed from tags afterwards. Commented Sep 6, 2019 at 13:43

2 Answers 2

5

"Hello" is stored ... in the DATA segment

"DATA" or .data would refer to the segment where initialized read/write variables with static storage duration go. String literals are not stored there, but more likely in something called .rodata, or possibly in .text along with the code. See String literals: Where do they go?

So isn't it better to always declare it: const char* str = "Hello";

Yes, you should always const qualify pointers to string literals. This is universally considered best practice in C (and mandatory in C++).

Sign up to request clarification or add additional context in comments.

Comments

0

Yes, it is better to declare pointers to string literals as const char *. The name "literal" very strongly suggests that this is something that is supposed to be immutable. Unfortunately, C treats string literals as arrays of char, not const char, and unlike numeric literals storage for the string literal must be allocated from somewhere. It is not guaranteed that this storage will be taken from a read-only segment like .rodata - I've worked with implementations in the past where string literals were writable.

The behavior on attempting to modify the contents of a string literal is undefined - the language places no requirement on the compiler or the runtime environment to handle the situation in any particular way. You may get a runtime error, or the string may be left unchanged, or the string may be modified, any something entirely different could happen.

So by declaring the pointer as const char *, you're at least making it harder to accidentally modify a literal through that pointer. Just remember that const doesn't mean "put this thing in read-only memory" - it only means "issue a diagnostic if someone tries to modify this thing".

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.