Sunday, May 1, 2011

The dangers of C++ string literals and non-const pointers

Foreword: I originally gained insight into this issue from Pete Isensee's blog post "When it Rains".

For years I used to take this line of C++ code for granted:

const char* str = "abcdef";

However, const protects you from altering the defined string literal values which is a good programmer habbit.

Question:
Why is this important, and why do most programmers use it?

Answer:
It's very important because according to the standard 2.13.4/2 "the effect of attempting to modify a string literal is undefined"

Question:
What is the correct way to alter strings?

Answer:
If you want to dynamically change string values use a character array because it creates a copy of the string. Moreover, the character array will terminate nicely with the null character '\0'.

Correct declaration and defintion:
char str[] = "abcdef";

Don't do this because it is undefined:
char* str = "abcdef";
str[0] = 'k';

Do this instead:
char str[] = "abcdef";
str[0] = 'k';

No comments:

Post a Comment