Pointers to Constant Strings

Learn about string literals and pointer to constant strings.

String literals

In the previous lesson, we saw that it’s possible to initialize a string as follows:

char str[10] = "abc";

The "abc" value is called a string literal. It is a sequence of characters terminated by the null character ('\0'). They are constant strings that we can’t modify.

Most commonly, they’re placed in the .rodata section of the executable file because they are constant and shouldn’t be modified, only read.

If the same string literal appears multiple times in the code, a smart compiler will only allocate it once inside .rodata and make all references inside the code point to the same literal.

To create a pointer to such strings literals, we can use the following syntax:

const char *ptr = "abcd";

We prefix the pointer as const because string literals are constant. The ptr pointer points to read-only or constant memory. It points to the beginning of the memory block allocated for "abcd".

Let’s define two pointers ptr1 and ptr2 to a string literal "abcd" and then explore the .rodata section to see its contents. To do this, we use the objdump command, which allows us to see the contents of the executable file generated from the code compilation process.

Get hands-on with 1400+ tech skills courses.