🚀 Learn BLE on Linux (BlueZ) – Programming Part 1
Hands-on Bluetooth Low Energy course. Special price: ₹399
Enroll Now on Udemy →Safe Pointer String Handling
Chapter 9, Strings: see which operations on string pointers in C crash your program, and learn three safe ways to give a char pointer real, writable memory. Free embedded C course by EmbeddedPathashala.
A pointer is only an address, so string pointers in C are safe only when that address leads to memory you are allowed to use. In this lecture of our free C programming course you will study the classic ways a char pointer goes wrong, then fix each one with a safe pattern. The patterns apply directly to embedded C programming, where a single bad pointer can freeze a device in the field.
Topics in This Lecture
What You Will Learn
- Why writing through a pointer to a string literal is undefined behaviour.
- Why reading input into an uninitialised pointer is a serious bug.
- How to allocate memory with
malloc, check for failure, and release it withfree. - How a static buffer avoids heap use, which many embedded projects require.
- How to read user text with a size limit instead of an unlimited format.
Prerequisites
You should have read the previous lecture on arrays and pointers as strings, and you should know the basics of pointers, malloc and free from the Pointers chapter of this free C tutorial.
Three Ways a String Pointer Goes Wrong
Every bug in this section compiles. Some of them even seem to work on one machine and fail on another, which is exactly what makes them dangerous. Study the patterns so you recognise them in other people’s code. Do not run the snippets in this section, because they are examples of faults.
| Fault | Example | What happens |
|---|---|---|
| Writing into a literal | char *p = "boot"; p[0] = 'B'; | Undefined behaviour, often a crash or hard fault |
| Uninitialised pointer | char *p; scanf("%s", p); | Input is written to a random address |
| Dangling pointer to a local | char *f(void) { char t[8] = "x"; return t; } | Caller receives an address whose storage is already gone |
Writing Into a String Literal
A literal belongs to the program image. Compilers are free to place it in read-only memory and to merge identical literals into one. Modifying it therefore has no defined meaning. Use const char * for pointers to literals, so that the compiler stops you before the program runs.
Reading Into an Uninitialised Pointer
A local pointer without an initialiser contains whatever bytes were on the stack before. Passing it to an input function tells the function to store text at that random place. The result may be a crash, or worse, a silent overwrite of another variable. A pointer must always point at real storage before you write through it.
Returning a Pointer to a Local Array
Local arrays live in the stack frame of the function. When the function returns, that space is reused by the next call. The pointer you returned still holds the old address, but the characters there will change unpredictably. Return a pointer to static storage, to memory supplied by the caller, or to heap memory instead.
Safe Sources of Storage for a char Pointer
| Source of memory | Lifetime | Writable? | Embedded suitability |
|---|---|---|---|
| String literal | Whole program | No | Excellent for fixed text |
| Static or global array | Whole program | Yes | Excellent, size known at link time |
| Local array in the caller | Until the caller returns | Yes | Good, watch stack depth |
| malloc block | Until free is called | Yes | Often restricted or forbidden |
Fix One: Allocate With malloc and Check the Result
When you really need dynamic memory, ask for it, verify the answer, use it with a size limit, and give it back. Save the following as ep_heapname.c:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(void)
{
char *buf = malloc(16);
if (buf == NULL) {
fputs("no memory\n", stderr);
return 1;
}
printf("Enter device name: ");
if (fgets(buf, 16, stdin) == NULL) {
free(buf);
return 1;
}
buf[strcspn(buf, "\n")] = '\0'; /* remove the trailing newline */
printf("Stored: %s (%zu chars)\n", buf, strlen(buf));
free(buf);
return 0;
}
$ gcc -std=c11 -Wall -Wextra -o ep_heapname ep_heapname.c
$ ./ep_heapname
Enter device name: spi_master
Stored: spi_master (10 chars)
Several details matter here. The result of malloc is tested before use, because it returns NULL when memory runs out. The call to fgets receives the buffer size, so a longer line is cut off instead of overflowing. The line strcspn finds the newline that fgets keeps and overwrites it with a terminator. Finally every exit path releases the block, and the program ends with no leak.
Warning: scanf("%s", buf) has no size limit and will overflow a small buffer. If you must use scanf, give a field width such as %15s for a sixteen-byte buffer. The fgets approach is easier to get right.
Fix Two: Use a Static Buffer and No Heap
Many embedded teams forbid malloc after start-up. Heap fragmentation can cause failures after days or months of operation, and the failures are almost impossible to reproduce on the bench. Coding standards such as MISRA C:2012 go as far as prohibiting the standard memory allocation functions. A fixed buffer chosen at compile time has none of these problems:
#include <stdio.h>
static char name_store[16];
int main(void)
{
char *name = name_store;
snprintf(name, sizeof name_store, "%s", "can_bus_0");
printf("name = %s\n", name);
printf("sizeof name_store = %zu, sizeof name = %zu\n",
sizeof name_store, sizeof name);
return 0;
}
$ ./ep_static
name = can_bus_0
sizeof name_store = 16, sizeof name = 8
The pointer name now refers to real, writable memory that exists for the whole run of the program. Notice that the size passed to snprintf is sizeof name_store, the array, and not sizeof name. The second line of output shows why: the pointer reports only its own size (8 on a 64-bit computer, 4 on a typical microcontroller). This one habit prevents a whole family of truncation and overflow bugs.
Fix Three: Let the Caller Supply the Buffer
A function that needs to produce text should receive both the buffer and its capacity, then report whether the text fitted. This keeps ownership clear: the caller decides where the memory lives, and the function never needs to allocate or return a dangling address. Signature shape, for example: int ep_format_name(char *out, size_t cap, int id), returning zero for success and a negative value when the text would not fit.
Real-World Use Cases
- Reading a configuration value over a serial console into a fixed-size buffer.
- Storing a user-chosen device or network name in a static structure field.
- Formatting diagnostic text into a reusable log buffer without allocating memory.
- Parsing commands where tokens are pointers into the same receive buffer.
Common Mistakes and Troubleshooting
- Not checking malloc. On a small system, running out of memory is a real possibility.
- Forgetting free. Every successful allocation needs one matching release, on every path.
- Using the block after free. Set the pointer to
NULLafter releasing it to make later misuse obvious. - Using sizeof on the pointer. It returns the pointer size, not the buffer size.
- Leaving the newline in the data.
fgetskeeps it, which breaks later string comparisons.
Best Practices, Performance and Security
- Initialise every pointer, either to valid storage or to
NULL. - Declare pointers to read-only text as
const char *. - Prefer static or caller-supplied buffers in firmware, and keep heap use for desktop tools.
- Always pass a size limit to input and formatting functions.
- Run tests under AddressSanitizer with
-fsanitize=address, which reports use-after-free, overflow and leaks with a clear stack trace.
As for performance, heap allocation is slower and less predictable than static storage, which matters for real-time work. From the security side, unchecked string input is the origin of many remote exploits, so every unbounded read is a defect to remove.
Summary and Key Takeaways
- A char pointer is only safe when it points to storage you may use.
- Never write through a pointer to a literal, an uninitialised pointer or a dangling pointer.
- With malloc: check for NULL, bound your input, and free exactly once.
- Static buffers and caller-supplied buffers avoid the heap and suit embedded targets.
- Use the array size, not the pointer size, when you pass a capacity.
Conclusion
Handling string pointers in C comes down to a single question: where do the bytes live, and who owns them? Once you can answer that for every pointer in your code, the three classic faults disappear. This habit is valuable in every lecture of this free embedded C course and in every firmware project you will ever read. In the final lecture of this series you will move from single strings to collections of strings by building arrays of strings and a short quiz.
Frequently Asked Questions
Why is it unsafe to modify a string literal through a pointer?
Literals may be stored in read-only memory, and the language does not define what happens when you write to them. The program may crash, fault or appear to work.
What happens if I pass an uninitialised char pointer to scanf?
The input is written to whatever address the pointer happens to contain, which corrupts memory or crashes the program.
Why do many embedded projects avoid malloc?
Heap fragmentation and allocation failure can cause rare, hard to reproduce faults in long-running devices, so fixed buffers are preferred.
How do I read a line safely into a char buffer?
Use fgets with the buffer size, then remove the trailing newline, for example with strcspn.
Why use sizeof on the array rather than on the pointer?
The array size is the real capacity. The pointer size is only the width of an address, so it would silently truncate your text.
Build Safe C Habits for Free
Safe pointer handling is the skill that separates hobby code from professional firmware. Keep practising with this free C programming course and move on to the final lecture of the chapter.

2 Comments