🚀 Learn BLE on Linux (BlueZ) – Programming Part 1
Hands-on Bluetooth Low Energy course. Special price: ₹399
Enroll Now on Udemy →String Pitfalls, Quiz, Interview
Learn the seven classic C string mistakes, how to fix them, then test yourself with a quiz and embedded C interview questions.
What You Will Learn
- Why a pointer needs real storage before you write through it
- Why string literals must not be modified and how const helps
- Why strcat needs a string and why array names cannot be assigned
- How dangling pointers and pointer parameters really behave
- How to answer common embedded C interview questions on strings
Prerequisites
- Lectures cp9_48 to cp9_53
- Arrays, pointers and functions
- Basic understanding of stack memory
The answer key at the end of the Strings chapter is a list of programs that look innocent and fail in instructive ways. In this final lecture of the batch, part of our free C programming course, we turn each failure into a rule you can remember. You will learn the most common C string mistakes, why each one happens, and how to fix it. Then you will test yourself with a quiz and a set of interview questions on embedded C programming and strings.
These bugs are the ones that cause real field failures: a pointer that was never set, text that cannot be modified, a buffer that outlives its function. Each is a few characters of source, and each is easy to avoid once you know the memory model behind it.
Mistake 1: Reading Into a Pointer That Points Nowhere
Declaring char *str; creates a pointer variable but no text storage. A local pointer holds whatever bytes were on the stack, so handing it to an input function such as fgets or scanf makes the function write to a random address. The same trap appears with an array of pointers: each element is uninitialised until you assign something valid to it.
char *str; /* points nowhere */
fgets(str, 32, stdin); /* BUG: writes to a random address */
char line[32]; /* FIX: real storage */
fgets(line, sizeof line, stdin);
Rule: before any function writes through a pointer, ask which object that pointer points to. If the answer is nothing, you have a bug.
Mistake 2: Modifying a String Literal
A string literal such as "Good" usually lives in read-only memory. A pointer to it is a view, not a copy. Writing through that pointer is undefined behaviour: on a PC it crashes, on a microcontroller it may silently do nothing. The array form creates a private writable copy.
char *p = "Good";
p[0] = 'g'; /* BUG: modifies read-only data */
char a[] = "Good";
a[0] = 'g'; /* FIX: the array is your copy */
const char *q = "Good"; /* BEST for read-only use: the compiler enforces it */
| Form | Where the characters live | Can you write? |
|---|---|---|
char a[] = "Good"; | Array, usually RAM | Yes |
const char *q = "Good"; | Read-only data, usually flash | No, and the compiler says so |
char *p = "Good"; | Read-only data | Compiles, but writing is undefined behaviour |
Mistake 3: Appending a Character With strcat
strcat joins two strings. The character '?' is a single small integer, not a string, so passing it makes the function treat the number 63 as an address and read from there. The fix is to pass the string "?", which is the two bytes ? and \0. Remember also that the destination must have enough room for both parts plus the terminator.
char msg[24] = "Ready";
strcat(msg, '?'); /* BUG: a char is not a string */
strcat(msg, "?"); /* FIX: a string literal */
Mistake 4: Assigning to an Array Name
An array name is not a variable that stores an address. It is the address of the first element, fixed for the lifetime of the array, so it cannot be the left side of an assignment. To put new text into an array, copy it with strcpy, snprintf or memcpy. Here is what a real compiler says:
char name[10];
name = "Asha";
bad_assign.c: In function 'main':
bad_assign.c:7:10: error: assignment to expression with array type
7 | name = "Asha";
| ^
The fix is snprintf(name, sizeof name, "%s", "Asha"); or strcpy when you have verified the length. The sizeof line in our fixed program below also shows the difference: a four letter array reports 5 bytes, the terminator included, while a pointer reports the size of an address, usually 8 on a 64-bit system.
Mistake 5: Returning the Address of a Local Array
A local array lives in the function’s stack frame. When the function returns, the frame is released and the next call may overwrite those bytes. A pointer to it becomes dangling. The program may even print the right text a few times, which makes the bug harder to find. There are three correct designs.
| Design | Who owns the memory | Typical use |
|---|---|---|
| Caller passes a buffer and its size | Caller | Best default; no heap, thread safe |
| Function returns a heap block | Caller must free | When the size is unknown in advance |
| Function returns a pointer to a literal or static const | Nobody; it lives forever | Fixed text such as error names |
Mistake 6: Changing a Pointer Parameter and Expecting the Caller to See It
When you pass an array to a function, the function receives a pointer: a copy of the address. Assigning a new address to that parameter changes only the copy. The caller’s array is untouched. To change the array contents you must write through the pointer. To change which object a caller’s pointer refers to, you need a pointer to the pointer.
Mistake 7: Misreading Adjacent Literals and Line Continuation
Two string literals separated only by whitespace are joined by the compiler into one. That is a convenient way to write long messages, but a missing comma in an array of strings merges two entries silently and shifts every index after it. A backslash at the very end of a line continues a literal on the next line, and any spaces at the start of that next line become part of the string.
All the Fixes in One Program
#include <stdio.h>
#include <string.h>
/* Safe replacement for "return the local array": caller owns the buffer. */
static void make_label(char *dst, size_t cap, int id)
{
snprintf(dst, cap, "node-%02d", id);
}
/* Rebinds only this function's private copy of the pointer. */
static void rebind_only(char *x)
{
x = "Jack";
(void)x;
}
/* Writes through the pointer, so the caller's array changes. */
static void write_through(char *x)
{
strcpy(x, "Jill");
}
int main(void)
{
char label[16];
char writable[] = "good"; /* array: a private, writable copy */
char msg[24] = "Ready";
char arr[8] = "";
const char *joined = "baud=" "115200" " parity=none";
const char *folded = "part one, \
part two";
make_label(label, sizeof label, 7);
printf("label : %s\n", label);
writable[0] = 'G';
printf("writable : %s\n", writable);
strcat(msg, "?"); /* "?" is a string, '?' is not */
printf("strcat : %s\n", msg);
printf("sizeof array=%zu, sizeof pointer=%zu\n",
sizeof writable, sizeof joined);
rebind_only(arr);
printf("after rebind_only : [%s]\n", arr);
write_through(arr);
printf("after write_through: [%s]\n", arr);
printf("%s\n%s\n", joined, folded);
return 0;
}
gcc -std=c11 -Wall -Wextra -pedantic -o pitfalls_fixed pitfalls_fixed.c
./pitfalls_fixed
label : node-07
writable : Good
strcat : Ready?
sizeof array=5, sizeof pointer=8
after rebind_only : []
after write_through: [Jill]
baud=115200 parity=none
part one, part two
Read the output against the code. The label comes from a caller-owned buffer, the writable array changed its first letter, strcat worked with a string, rebind_only left the array empty while write_through filled it, and both literal forms printed as one string.
Best Practices, Performance and Security
- Compile with
-Wall -Wextra -pedanticand treat warnings as errors; most mistakes above produce a warning. - Declare read-only text as
const char *so writes are rejected at compile time. - Pass buffer sizes with every buffer. Prefer
snprintfandmemcpywith checked lengths over unbounded calls. - Initialise every pointer, to a valid object or to
NULL, and test forNULLbefore use. - Run tools such as AddressSanitizer on a PC build of your firmware logic; it finds dangling pointers and overflows that hardware hides.
- Many security vulnerabilities in the field are string bugs: overflowed buffers, missing terminators and unchecked lengths.
Quiz: Test Your Understanding
Try each question before you open the answer.
- What does
char *s;create?Show answer
A pointer variable only, with an indeterminate value. There is no text storage behind it.
- Which is safe to modify:
char a[] = "ok";orchar *p = "ok";?Show answer
The array. The pointer refers to a literal that may be in read-only memory.
- What is wrong with
strcat(msg, '!');?Show answer
A character is not a string. Use
"!". - Why is
name = "Asha";illegal forchar name[10]?Show answer
An array name is a fixed address, not an assignable variable. Copy the text in.
- Why is returning a local array dangerous?
Show answer
Its stack frame is released when the function returns, so the pointer dangles.
- Output of:
char s[] = "embed"; s[2] = 'X'; puts(s);Show answer
emXed - Output of:
char a[8] = "ab"; strcat(a, "cd"); printf("%zu %zu", strlen(a), sizeof a);Show answer
4 8: the length is four, the array is eight bytes. - Output of:
printf("%s", "go" "al");Show answer
goal, because adjacent literals are joined. - A function does
x = "hi";on itschar *xparameter. Does the caller’s arrayb[4] = "no"change?Show answer
No. It prints
no; only the local pointer copy was rebound. - What are
strlen(t)andsizeof tforchar t[] = "ab\0cd";?Show answer
2and6.strlenstops at the first zero byte;sizeofcounts the whole array including the final terminator.
Embedded C Interview Questions on Strings
- What is the difference between
char a[]andchar *pfor a string?Show answer
The array owns writable storage and its name is a fixed address; the pointer is a variable that can point anywhere, including to read-only literal data.
sizeofreports the array size for the first and the pointer size for the second. - Why must a function that fills a buffer also receive its size?
Show answer
Because a pointer carries no length. Without the size the function cannot prevent overflow.
- Why is
getsremoved from the language?Show answer
It cannot be told how large the buffer is, so any long input overflows it. Use
fgetswithsizeof. - How would you implement
strlen?Show answer
Walk a pointer to the terminator and subtract the start address, returning
size_t. - What is the difference between
memcpyandmemmove?Show answer
memmovehandles overlapping regions;memcpydoes not. - Why might a string literal be placed in flash on a microcontroller?
Show answer
Literals are constant, so the toolchain keeps them in read-only memory to save RAM. That is why you declare pointers to them as
const char *. - How do you delete characters from a string in place?
Show answer
Use a read pointer and a write pointer, copy only the characters to keep, and write a new terminator.
- What does
strcmpreturn, and why not use==?Show answer
It returns negative, zero or positive according to ordering of the first differing characters. The operator
==compares addresses, not contents. - What is a dangling pointer? Give a string example.
Show answer
A pointer to storage that no longer exists, such as the address of a local array returned from a function.
- How do you sort an array of strings cheaply?
Show answer
Keep an array of pointers and swap the pointers according to
strcmp, instead of copying characters. - What bugs does
constprevent in string code?Show answer
It turns accidental writes through pointers to read-only text into compile-time errors.
- How can a missing comma break a table of strings?
Show answer
Adjacent literals are concatenated, so two entries merge into one and every later index shifts by one.
Mini Challenge
Take any string function from the last six lectures and write three deliberately bad calls for it: a literal as the destination, a destination that is too small and a NULL pointer. Decide in advance what each should do, then make the function behave that way. That exercise is exactly what a code reviewer does.
Key Takeaways
- A pointer needs real storage before any function writes through it.
- Literals are read-only; use arrays to edit and
const char *to read. - Pass strings, not characters, to
strcat, and never assign to an array name. - Never return a local array; let the caller supply the buffer and its size.
- Changing a pointer parameter affects only the local copy; writing through it affects the caller.
Conclusion
Every mistake in this lecture comes back to the same question: which memory does this pointer refer to, and who owns it? Once you answer that automatically, string bugs stop being mysterious. They become routine items on a code review checklist.
You have now finished this batch of the Strings chapter: counting, editing, trimming, encoding, sorting, tables and pitfalls, all with original examples you can compile and extend. Keep practising with the challenges, then continue the free embedded C course with the next chapter. If this helped you, share this free C programming course with a friend who is starting embedded C programming.
Frequently Asked Questions
Why does my C program crash when I change a string?
You are probably writing to a string literal through a char *. Copy the literal into a char array or use const char * and do not write.
Why can I not assign a string to a char array?
An array name is a fixed address and cannot be assigned. Copy with strcpy or snprintf.
What is wrong with returning a local array from a function?
The array is destroyed on return, leaving a dangling pointer. Let the caller provide the buffer.
Does changing a pointer parameter change the caller’s array?
No. The function holds a copy of the address. Write through the pointer to change the contents.
What does the compiler do with two adjacent string literals?
It joins them into one literal, which is convenient but hides a missing comma in a table of strings.
Where can I practise more C string questions for free?
This free embedded C course and its free C tutorial series offer more lectures with quizzes and interview questions.
Keep Going With the Free Embedded C Course
EmbeddedPathashala teaches embedded C programming, Linux kernel development and device drivers for free. Pick the next lecture and keep your streak going.

2 Comments