🚀 Learn BLE on Linux (BlueZ) – Programming Part 1
Hands-on Bluetooth Low Energy course. Special price: ₹399
Enroll Now on Udemy →Free C Programming Course · Strings · Lecture 41
C String Pitfalls and Quiz
Six classic string bugs, safe fixes, a 10-question quiz and interview questions. The final lecture of the Strings chapter in our free C tutorial.
Most string bugs in C come from the same few mistakes: a missing terminator, a buffer that is too small, or text that was never meant to be modified. They compile cleanly and often seem to work, until the day they corrupt memory on a customer’s device. In this final lecture of the Strings chapter of our free C programming course you will study six C string pitfalls, see the safe version of each, and then test yourself with a quiz and interview questions. It rounds off the chapter for anyone following our free embedded C course or preparing for embedded C programming interviews.
What You Will Learn
- What happens when a char array has no NUL terminator
- The difference between sizeof and strlen
- Why string literals must not be modified
- How to concatenate and format text without overflowing
- Why gets is gone and fgets replaced it
- How to answer common string interview questions
Prerequisites
You should have completed the earlier lectures of this Strings chapter, including string input and output, strlen, strcpy, strcat and arrays of strings.
Memory Picture: Terminated and Unterminated Arrays
A C string is only a convention: a run of characters ending with a zero byte. If the zero is missing, string functions keep reading until they happen to meet one somewhere in memory.
Same letters, very different safety
Pitfall 1: The Missing Terminator
Initialising an array with exactly as many characters as it has slots leaves no room for the NUL. Printing it with %s then runs off the end. If the array is larger, the unused slots are zero-filled automatically, so the string is fine.
Pitfall 2: sizeof Versus strlen
| Declaration | sizeof | strlen | Why |
|---|---|---|---|
char a[8] = "Embd"; | 8 | 4 | sizeof is the whole array, strlen stops at the NUL |
char a[] = "Embd"; | 5 | 4 | compiler sizes the array to include the NUL |
const char *p = "Embd"; | size of a pointer | 4 | sizeof a pointer says nothing about the text |
Pitfall 3: Modifying a String Literal
A literal such as "boot" normally lives in read-only memory. A pointer to it must be const, and writing through it is undefined behaviour, often a crash on embedded targets where the text sits in flash. If you need to change the text, copy it into an array: char text[] = "boot";. The same rule explains why strcat onto a pointer that points to a literal fails: there is no room after the literal, and it is not writable anyway.
Pitfall 4: Concatenating Without Checking Size
strcat does not know how big the destination is. You have to check that the existing length plus the new length plus one for the terminator fits.
Pitfall 5: Silent Truncation
snprintf is safe against overflow, but if the text does not fit it quietly cuts it. Its return value tells you how many characters it wanted to write, so compare that with the buffer size whenever truncation would matter.
Pitfall 6: Reading Input with gets
The old gets function has no size limit and was removed from the language in C11. It also appears in old textbooks paired with an uninitialised pointer, which is a second bug: a pointer that points nowhere cannot hold text. Read into a real array with fgets, and remember that it keeps the newline.
Warning: a pointer declared as char *s; contains garbage until you assign it. Passing it to scanf("%s", s) or any copy function writes to a random address. Always point it at an array or at memory from malloc first.
Demo Program: All Six Pitfalls and Their Fixes
#include <stdio.h>
#include <string.h>
int main(void)
{
/* 1. array filled with chars but no terminator */
char raw[4] = {'E', 'm', 'b', 'd'};
printf("raw: sizeof=%zu (no NUL inside, never print with %%s)\n", sizeof raw);
/* 2. terminator present */
char ok[8] = {'E', 'm', 'b', 'd'}; /* rest is zero-filled */
printf("ok : sizeof=%zu strlen=%zu text=%s\n", sizeof ok, strlen(ok), ok);
/* 3. literal vs array: only the array may be modified */
char writable[] = "boot";
const char *readonly = "boot";
writable[0] = 'B';
printf("writable=%s readonly=%s\n", writable, readonly);
/* 4. safe concatenation with a size check */
char path[16] = "/dev/";
const char *name = "ttyS0";
if (strlen(path) + strlen(name) < sizeof path) {
strcat(path, name);
printf("joined: %s\n", path);
}
const char *too_long = "a_very_long_device_name";
if (strlen(path) + strlen(too_long) >= sizeof path)
printf("refused: '%s' would overflow %zu bytes\n", too_long, sizeof path);
/* 5. snprintf reports truncation */
char small[8];
int need = snprintf(small, sizeof small, "%s", "temperature");
printf("snprintf wanted %d chars, stored '%s'\n", need, small);
/* 6. fgets instead of gets */
char line[8];
printf("type something long: ");
if (fgets(line, sizeof line, stdin)) {
line[strcspn(line, "\n")] = '\0';
printf("kept: '%s'\n", line);
}
return 0;
}
Build and Run
$ gcc -std=c11 -Wall -Wextra -o pitfalls pitfalls.c
$ echo "abcdefghijkl" | ./pitfalls
GCC may warn that the snprintf output will be truncated. That warning is correct and intended: the line demonstrates truncation on purpose.
Expected Output
raw: sizeof=4 (no NUL inside, never print with %s)
ok : sizeof=8 strlen=4 text=Embd
writable=Boot readonly=boot
joined: /dev/ttyS0
refused: 'a_very_long_device_name' would overflow 16 bytes
snprintf wanted 11 chars, stored 'tempera'
type something long: kept: 'abcdefg'
Notice the last two lines. The temperature string needed 11 characters but only 7 fit in an 8-byte buffer. The long input was cut to 7 characters because fgets always leaves one byte for the terminator.
Safe String Checklist for Embedded C Programming
| Situation | Safe habit |
|---|---|
| Declaring text you will edit | use an array, not a pointer to a literal |
| Declaring text you will only read | use const char * |
| Copying or joining | check the lengths, or use snprintf and test its return |
| Reading a line | fgets with sizeof of the buffer |
| Buffer size | always count the terminator |
| Pointers | initialise before use, set to NULL when unused |
Security and Performance Notes
- Buffer overflows from strings are one of the most common causes of security holes in firmware, including remote code execution through a network packet.
- Bounded functions cost a few extra instructions, which is a tiny price compared with a crash in the field.
- Keep fixed-size buffers small but sufficient, and define their sizes once as named constants.
Quiz: Test Your Understanding
Try each question first, then open the answer.
Q1. What is wrong with printing char s[4] = {'a','b','c','d'}; using %s?
Show answer
There is no terminating zero, so printf reads beyond the array. The behaviour is undefined.
Q2. For char a[10] = "hi"; what do sizeof(a) and strlen(a) return?
Show answer
sizeof(a) is 10 and strlen(a) is 2.
Q3. For char a[] = "Embd"; what is sizeof(a)?
Show answer
5. Four letters plus the terminator.
Q4. Is const char *p = "boot"; p[0] = 'B'; legal?
Show answer
It may compile if the const is missing, but modifying a string literal is undefined behaviour and usually crashes.
Q5. Why is char *s; scanf("%s", s); a bug?
Show answer
The pointer is uninitialised, so scanf writes to a random address. It also has no length limit.
Q6. What does snprintf return when the output is truncated?
Show answer
The number of characters that would have been written if there had been enough space, not the number actually stored.
Q7. Which C standard removed gets?
Show answer
C11.
Q8. What does fgets do with the newline typed by the user?
Show answer
It stores it in the buffer if there is room, so you usually remove it, for example with strcspn.
Q9. What does strcmp(“apple”, “banana”) return?
Show answer
A negative value, because “apple” comes before “banana”. Only the sign is guaranteed, not the exact number.
Q10. In freq[ch]++, why cast ch to unsigned char?
Show answer
A plain char can be negative, which would index before the start of the array.
Programming Challenges
- Challenge 1: Write
int safe_join(char *dst, size_t cap, const char *a, const char *b)that joins two strings and returns -1 if they do not fit. - Challenge 2: Extend the frequency counter to print the most common character and its count.
- Challenge 3: Write a function that reports whether a string is a valid unsigned hexadecimal number, then convert it with your own routine.
- Challenge 4: Combine this chapter: read a number as text, parse it safely, and print it in words.
Interview Questions on C Strings
1. How is a string stored in C?
Show answer
As an array of chars ending with a zero byte. There is no separate length field, so the terminator is the only marker.
2. What is the difference between char s[] = “abc” and char *s = “abc”?
Show answer
The first creates a modifiable array holding a copy of the text. The second creates a pointer to a read-only literal.
3. Why is strcpy considered dangerous?
Show answer
It does not know the destination size, so a long source overflows the buffer. Check lengths first or use a bounded alternative such as snprintf.
4. What is the problem with strncpy?
Show answer
If the source is as long as the limit, it does not add a terminator. It also pads short strings with zeros, which wastes time. Many teams prefer snprintf.
5. How do you reverse a string in place?
Show answer
Use two indices, one at the start and one at the last character, and swap while the first is less than the second.
6. How would you convert a string to an integer safely?
Show answer
Use strtol and check the end pointer and errno, or write a parser that rejects empty input, trailing junk and overflow, as in Lecture 38.
7. Why avoid printf with %f on small microcontrollers?
Show answer
Float support adds large code to the library and is often disabled. Fixed-point formatting using integers is smaller and predictable.
8. How do you stop a buffer overflow when reading input?
Show answer
Use fgets with sizeof of the buffer, validate the length, and never use gets or scanf with an unbounded %s.
9. What does sizeof return for a char pointer?
Show answer
The size of the pointer itself, typically 4 bytes on 32-bit MCUs and 8 on 64-bit systems, not the length of the text.
10. How would you count character frequency efficiently?
Show answer
Use a 256-entry table indexed by unsigned char and make one pass over the string. See Lecture 36.
Suggested Images
| Image idea | Suggested ALT text |
|---|---|
| Terminated and unterminated char arrays side by side | C string pitfalls missing null terminator, free C programming course |
| Memory map showing literal in flash and array in RAM | string literal vs char array in embedded C programming, free C tutorial |
| Quiz card with ten questions | C strings quiz and interview questions, free embedded C course |
Summary and Key Takeaways
- Every string needs a NUL terminator and a buffer big enough to hold it.
- sizeof measures storage; strlen measures text.
- Never modify a string literal; copy it into an array first.
- Check lengths before strcat, and check snprintf’s return value.
- Use fgets, never gets, and always initialise pointers.
Conclusion
This lecture closes the Strings chapter of our free C programming course. You can now read, count, parse, format and protect text in C, which is most of what real firmware does with strings. Revisit any lecture you found hard, redo the challenges without looking, and move on to the next chapter of this free embedded C course.
Frequently Asked Questions
Is it ever safe to use strcpy?
Yes, when you have already proved the source fits, for example by checking its length first. Otherwise use a bounded method.
Why does my string print garbage after the text?
Most likely the terminator is missing or was overwritten, so the print continues into neighbouring memory.
What is the difference between NULL and the NUL character?
NULL is a null pointer. NUL is the zero byte written as ‘\0’ that ends a string.
Can I compare strings with ==?
No. That compares addresses. Use strcmp to compare the text.
Should I use strlen in a loop condition?
Avoid it when the string does not change, because it scans the whole string each time. Store the length first or test for the terminator.
Where can I practise more?
Repeat the challenges above on a real board using a serial terminal, and compare your results with snprintf.
You Finished the Strings Chapter
Well done. Keep going with the free C programming course and build the skills employers look for in embedded C programming.

2 Comments