Anton Andreev
Anton Andreev

Reputation: 2132

char* vs const char* in C

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';

Upvotes: 0

Views: 186

Answers (2)

John Bode
John Bode

Reputation: 123458

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".

Upvotes: 0

Lundin
Lundin

Reputation: 213306

"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++).

Upvotes: 5

Related Questions