🚀 Learn BLE on Linux (BlueZ) – Programming Part 1
Hands-on Bluetooth Low Energy course. Special price: ₹399
Enroll Now on Udemy →C String Literal Tricks
Learn how c string literals really behave: indexing, offsets, adjacent concatenation and read-only storage.
Every time you write a quoted piece of text in a C program you are creating an object, and the rules around that object are stranger than most beginners expect. Understanding c string literals lets you index them, offset them, glue them together at compile time and avoid the classic crash that comes from trying to modify one. This lecture of our free C tutorial treats literals as what they really are: unnamed, usually read-only arrays of characters that the compiler places in memory for you.
What You Will Learn
- What a string literal is in memory, and where it usually lives on a microcontroller
- How to index a literal and add an offset to it directly
- Why
sizeofandstrlengive different answers for the same literal - How adjacent literals are joined by the compiler, and how a missing comma turns that feature into a bug
- How to build a string from numeric character codes
- Why writing to a literal crashes, and how to avoid it
Prerequisites
You should know what a NUL terminated string is, how strlen works, and the basics of pointers and arrays from the previous lectures in this free C programming course. A Linux or Windows machine with GCC (or any C11 compiler) is enough. All outputs here come from GCC 13 with -std=c11 -Wall -Wextra.
What Are C String Literals in Memory?
A literal such as "SENSOR" is an array of seven char values: the six letters followed by a NUL. It has no name, it exists for the whole run of the program, and in nearly every real toolchain it is placed in a read-only section of the binary. On a desktop that section is called .rodata; on a microcontroller it typically ends up in flash memory, which means it consumes no RAM at all unless you copy it somewhere.
This is why the two declarations below behave so differently even though they look similar. The first creates a modifiable copy in RAM. The second creates only a pointer, and the characters stay in read-only storage.
| Declaration | Where the characters live | Can you modify them? | Can you reassign the name? |
|---|---|---|---|
char a[] = "SENSOR"; | RAM array (initialised from the literal) | Yes | No, it is an array |
const char *p = "SENSOR"; | Read-only storage (flash or .rodata) | No, compiler enforces it | Yes, pointer can move |
char *p = "SENSOR"; | Read-only storage | Compiles, but writing is undefined behaviour | Yes |
Array copy versus pointer to a literal
Indexing and Offsetting C String Literals
Understanding c string literals starts with one fact: a literal is an array. Because arrays convert to pointers in expressions, you may apply both subscripts and pointer arithmetic to it directly, without storing it in a variable first. The program below shows the equivalent forms and then compares two measurements that are easy to confuse.
#include <stdio.h>
#include <string.h>
int main(void)
{
printf("%c\n", "SENSOR"[2]);
printf("%c\n", *("SENSOR" + 3));
printf("%s\n", "SENSOR" + 3);
printf("strlen=%zu sizeof=%zu\n", strlen("SENSOR"), sizeof("SENSOR"));
printf("%s\n", "TEMPERATURE" + strlen("OK"));
printf("%s\n", "TEMPERATURE" + sizeof("OK"));
return 0;
}
Compile with gcc -std=c11 -Wall -Wextra -o p43a p43a.c and run it:
N
S
SOR
strlen=6 sizeof=7
MPERATURE
PERATURE
The first line shows that "SENSOR"[2] is the character at index 2, namely N. The second and third lines show that a literal plus an offset behaves just like any pointer plus an offset. The most important lesson sits on the fourth line. strlen counts characters up to the NUL, so it returns 6. sizeof measures the whole array including the terminator, so it returns 7. When you use either one as an offset the difference is exactly one character, which is why the last two outputs differ by the letter E in TEMPERATURE.
When sizeof on a Literal Is Useful
Because sizeof on a literal is a compile-time constant that already includes the NUL, you can use it to skip a known prefix without counting by hand. A command parser might check that a line begins with "AT+" and then continue from line + sizeof("AT+") - 1. If the prefix text later changes, the offset updates itself. Using strlen for the same job also works and the compiler usually folds it into a constant, but be careful to subtract one when you reach for sizeof.
Adjacent String Literals Are Joined
When two literals appear side by side with only whitespace between them, the compiler merges them into one before the program ever runs. This lets you break a long message across several source lines without any runtime cost and without a backslash. It is a favourite trick in logging macros and boot banners.
The feature has a dark side. Inside an initialiser list, a forgotten comma silently glues two entries together. The program below was meant to hold four state names but only three elements exist, and the second one is wrong.
#include <stdio.h>
int main(void)
{
const char *states[] = {"IDLE", "INIT" "RUN", "FAULT"};
const char *banner = "Boot OK, "
"clock 168 MHz, "
"UART ready\n";
size_t i, n = sizeof(states) / sizeof(states[0]);
printf("count = %zu\n", n);
for (i = 0; i < n; i++)
printf("states[%zu] = %s\n", i, states[i]);
printf("%s", banner);
return 0;
}
count = 3
states[0] = IDLE
states[1] = INITRUN
states[2] = FAULT
Boot OK, clock 168 MHz, UART ready
There was no warning and no error. The array count is three, states[1] reads INITRUN, and any code that expects the fourth state at index 3 will read out of bounds. The multi line banner at the end, in contrast, is exactly the intended use of the feature. Both behaviours come from the same rule, so the defence is discipline: put one entry per line in a table of strings and end every line with a comma, including the last one, so a missing comma stands out in a code review.
What the compiler does with adjacent literals
Building a String From Numeric Character Codes
A character in C is just a small integer, and a string is just an array of those integers ending in zero. That means you can build text without writing any quotes at all, which is handy when a protocol hands you raw byte values. The terminating zero is the part people forget.
#include <stdio.h>
int main(void)
{
char tag[] = {'E', 'P', 0x2D, 49, 0};
printf("%s (sizeof %zu)\n", tag, sizeof tag);
return 0;
}
EP-1 (sizeof 5)
The code 0x2D is the dash and 49 is the digit 1 in ASCII, so the result reads EP-1. The array has five elements because the explicit trailing zero counts. If you leave it out, printf("%s") keeps reading memory until it stumbles on a zero byte somewhere, which is a classic source of garbage on a serial console.
Why Modifying C String Literals Crashes
The C standard says that changing a string literal is undefined behaviour. On a real system that usually means a fault, because the memory is mapped read-only. Here is the smallest example:
#include <stdio.h>
int main(void)
{
char *msg = "abc";
msg[0] = 'X';
printf("%s\n", msg);
return 0;
}
It compiles cleanly (older C compilers accept char * for a literal for historical reasons) but on Linux the run ends like this:
Segmentation fault
On a Cortex-M the same mistake shows up as a hard fault or, worse on some parts, as a silent no-op because flash ignores the write. Neither is what you intended. The cure is simple: declare pointers to literals as const char *, so the compiler stops you, or declare an array if you really need to edit the text.
Tip: never compare two string literals with ==. That compares addresses, and whether two identical literals share one address is up to the compiler. Use strcmp to compare contents.
Common Mistakes With String Literals
| Mistake | Consequence | Fix |
|---|---|---|
Writing through char *p = "text" | Crash or hard fault | Use const char * or a char array |
| Forgetting a comma in a table of strings | Two entries merge, array is one element short | One entry per line, trailing comma |
Using sizeof as a length | Off by one because the NUL is counted | Subtract one, or use strlen |
Comparing literals with == | Compares addresses, result is unreliable | Use strcmp |
| Hand-built array without a final 0 | String functions run past the end | Always end the list with 0 |
Best Practices for C String Literals
- Declare literal pointers as
const char *everywhere, including function parameters. - In embedded C programming keep fixed messages as
constdata so the linker places them in flash and RAM stays free. - Use adjacent literals to split long messages; it costs nothing at runtime.
- Turn on
-Wwrite-stringsso GCC warns when a literal is assigned to a plainchar *. - Never pass a literal to an API that might modify its argument, such as a tokenizer that writes NULs into the buffer.
For c string literals the performance angle is simple: identical literals can be merged by the linker, which saves flash. From a security angle, never pass attacker-controlled text as a format string; keep your literals as the format and pass data as arguments. We will see that failure in a later lecture of this free embedded systems course.
Summary and Key Takeaways
- A string literal is an unnamed array of char with a NUL at the end, normally stored in read-only memory.
- You can subscript it and add an offset to it directly.
sizeofcounts the NUL,strlendoes not.- Adjacent literals are merged at compile time, so a missing comma in a table of strings is a silent bug.
- The rules for c string literals are simple: read-only, NUL terminated, merged when adjacent.
- Writing to a literal is undefined behaviour; use
const char *or an array.
Conclusion
C string literals look like harmless text, yet they carry rules about storage, size and merging that affect every embedded project. If you remember only one thing, remember to type them as const char *; the compiler then guards the other four lessons for you. Try this challenge before moving on: write a function that takes a const char * and reports whether it starts with a given prefix, using sizeof on a literal to avoid magic numbers. It is a small exercise that makes the ideas in this free C programming course concrete, and it prepares you for the parsing lectures that follow.
Frequently Asked Questions
What are c string literals?
They are quoted text constants in C source code, such as “SENSOR”. The compiler stores each one as a NUL terminated array of char that lives for the whole program and is normally placed in read-only memory.
Why does modifying a string literal crash my program?
Literals are usually stored in read-only memory, and the standard makes any write to them undefined behaviour. On Linux this gives a segmentation fault, and on a microcontroller it can cause a hard fault.
What is the difference between sizeof and strlen for a literal?
sizeof gives the number of bytes in the array including the terminating NUL, while strlen counts characters before the NUL. For “SENSOR” they are 7 and 6.
How does adjacent string concatenation work in C?
When two string literals are separated only by whitespace, the compiler joins them into one literal before compilation finishes. “INIT” “RUN” becomes “INITRUN”.
Why does my array of strings have fewer elements than I wrote?
A missing comma between two literals merges them into one element. Place each entry on its own line with a trailing comma so the mistake is easy to spot.
Should I use char * or const char * for string literals?
Use const char *. It documents that the text is read-only and lets the compiler reject accidental writes, which is especially valuable in embedded firmware where literals live in flash.
Can I build a string from ASCII codes?
Yes. Put the numeric codes in a char array and end it with 0, for example {‘E’, ‘P’, 0x2D, 49, 0} gives “EP-1”. Without the trailing zero the array is not a valid string.
Keep Going With the Free C Course
EmbeddedPathashala is a free C programming course and free embedded C course built for students. Practice every example on your own machine, then move on to the next lecture.

2 Comments