What are Dangling and Wild String Pointers- Free Embedded Systems and C Programming Course

🚀 Learn BLE on Linux (BlueZ) – Programming Part 1

Hands-on Bluetooth Low Energy course. Special price: ₹399

Enroll Now on Udemy →
💬 Need help or career guidance? Ask us!Contact Us →

Free C Programming Course · Strings

Dangling and Wild String Pointers

Understand wild and dangling pointers in C strings, and fix them with arrays, malloc or caller-owned buffers.

Two pointer bugs cause a huge share of mysterious crashes in beginner firmware: a pointer that was never given a valid target, and a pointer that still holds the address of something that no longer exists. Both show up constantly when programs store text. This lecture explains dangling pointer in C strings problems and their wild cousins, shows real compiler warnings and crashes, and gives three reliable fixes. It continues our free C programming course with a focus on C for embedded systems.

What You Will Learn

  • The difference between a wild pointer and a dangling pointer
  • Why scanf into an uninitialised array of char * crashes
  • Two correct ways to store several input words: a 2-D array and per-word malloc
  • Why returning the address of a local array is a bug, and what GCC says about it
  • Three fixes: caller-owned buffer, static buffer and heap allocation, with their trade-offs

Prerequisites

You should be comfortable with arrays of characters, pointers, malloc and free, and the idea of automatic (stack) variables from the earlier lectures of this free C tutorial. We assume GCC 13 on Linux. The crash outputs below were produced on x86-64 Linux; on a microcontroller the same bug may appear as a hard fault or as silent corruption.

Wild Pointers Versus Dangling Pointers in C Strings

Spotting a dangling pointer in C strings starts with knowing the vocabulary. A wild pointer is a pointer that was declared but never assigned. A local pointer variable starts with whatever garbage was in that stack slot, so it may point anywhere. A dangling pointer was valid once, but the object it points to has since ended its lifetime: a local variable whose function returned, or heap memory that was freed. In both situations, reading or writing through the pointer is undefined behaviour. The difference is only in how you arrived there.

KindHow it appearsTypical symptomCure
Wild pointerDeclared, never initialised, then usedImmediate segmentation fault or corrupted dataInitialise to a valid object, or to NULL and check
Dangling (stack)Returned address of a local arrayGarbage text, crash, or a result that changesCaller supplies the buffer
Dangling (heap)Pointer used after freeIntermittent corruptionSet the pointer to NULL after free

The Wild Pointer Array Trap With scanf

The following program tries to read three words into an array of three string pointers:

#include <stdio.h>

int main(void)
{
    char *names[3];
    int i;

    for (i = 0; i < 3; i++)
        scanf("%15s", names[i]);
    printf("%s\n", names[0]);
    return 0;
}

It compiles without complaint, yet the array holds three uninitialised pointers. scanf faithfully tries to write the typed word at whatever address each one contains. Feeding it input and running it ends like this on our test machine:

printf 'motor valve pump\n' | ./p45bad
Segmentation fault

The crash is the lucky outcome. On a small microcontroller without memory protection the write may land on a peripheral register or on another variable and the program carries on, wrongly. The mistake is conceptual: an array of pointers holds addresses of storage, it is not storage itself.

Pointer array with no storage behind it

names slot 0→garbage address
names slot 1→garbage address
names slot 2→garbage address
scanf writes characters to those addresses, not into the array

Fix 1: Use a 2-D Character Array

If every word has a sensible maximum length, give the characters a home by declaring a two dimensional array. Each row is a complete buffer. The width in the format, %15s, leaves one byte of every 16 byte row for the terminator, so a longer word cannot overflow the row.

#include <stdio.h>

int main(void)
{
    char names[3][16];
    int i;

    for (i = 0; i < 3; i++)
        scanf("%15s", names[i]);
    for (i = 0; i < 3; i++)
        printf("[%s]\n", names[i]);
    return 0;
}
printf 'motor valve pump\n' | ./p45a
[motor]
[valve]
[pump]

Here the storage is 48 bytes, decided at compile time, with no heap involved. This suits embedded C programming, where predictable memory use matters more than saving a few bytes.

Fix 2: Allocate Each Word With malloc

When lengths vary a lot or the count is only known at run time, keep the array of pointers but give every slot a real buffer first. Always test the result of malloc and release every buffer.

#include <stdio.h>
#include <stdlib.h>

int main(void)
{
    char *names[3];
    int i;

    for (i = 0; i < 3; i++) {
        names[i] = malloc(16);
        if (names[i] == NULL)
            return 1;
        scanf("%15s", names[i]);
    }
    for (i = 0; i < 3; i++) {
        printf("[%s]\n", names[i]);
        free(names[i]);
    }
    return 0;
}
[motor]
[valve]
[pump]

The output is identical, but the memory story is different: three separate heap blocks, each of which you must free. In a bare metal project with no heap, or in a safety critical codebase that bans dynamic allocation, choose the 2-D array instead.

Pointer array after malloc

names slot 0→heap block of 16 bytes
names slot 1→heap block of 16 bytes
names slot 2→heap block of 16 bytes
Every pointer now owns storage, and every block needs a matching free

Dangling Pointer in C Strings: Returning a Local Array

The second classic dangling pointer in C strings bug is building a string inside a function and returning its address. A local array lives on the stack and is destroyed when the function returns, so the caller receives a pointer to space that will be reused by the very next call.

#include <stdio.h>

static char *make_tag(const char *kind, int id)
{
    char buf[32];

    snprintf(buf, sizeof buf, "%s-%02d", kind, id);
    return buf;
}

int main(void)
{
    char *t = make_tag("sensor", 7);
    printf("%s\n", t);
    return 0;
}

GCC notices the problem when warnings are enabled:

p45c.c: In function 'make_tag':
p45c.c:8:12: warning: function returns address of local variable [-Wreturn-local-addr]
    8 |     return buf;
      |            ^~~

Running the program is where it gets interesting. On our machine it crashed with a segmentation fault, but a different compiler or optimisation level may print garbage, or even print sensor-07 by luck. That unpredictability is the signature of undefined behaviour: you cannot rely on the “it worked once” result.

Stack frame lifetime in make_tag

call make_tag→buf created on stack→text written
return buf→frame destroyed→caller holds dangling address
The next function call may overwrite the same stack bytes

Three Fixes and Their Trade-Offs

You can make the function safe in three ways. The program below shows the first two side by side, so you can see both the benefit of the caller-owned buffer and the hidden catch of the static one.

#include <stdio.h>

static const char *tag_static(const char *kind, int id)
{
    static char buf[32];

    snprintf(buf, sizeof buf, "%s-%02d", kind, id);
    return buf;
}

static void tag_into(char *out, size_t cap, const char *kind, int id)
{
    snprintf(out, cap, "%s-%02d", kind, id);
}

int main(void)
{
    const char *a = tag_static("sensor", 7);
    const char *b = tag_static("valve", 3);
    char x[32], y[32];

    printf("static  : a=%s b=%s\n", a, b);

    tag_into(x, sizeof x, "sensor", 7);
    tag_into(y, sizeof y, "valve", 3);
    printf("callerbuf: x=%s y=%s\n", x, y);
    return 0;
}
static  : a=valve-03 b=valve-03
callerbuf: x=sensor-07 y=valve-03

Look at the first line. Both a and b print valve-03 because they point to the same static buffer, and the second call overwrote the first result. The caller-owned version has no such problem because each result has its own array.

ApproachMemoryStrengthWeakness
Caller passes a buffer and its sizeCaller decides (stack or static)Safe, re-entrant, no heapSlightly longer call
Function uses a static bufferOne fixed block for the whole programSimple to callOverwritten by the next call, unsafe with threads or interrupts
Function returns malloced memoryHeapAny lifetimeCaller must free; heap may be unavailable

Rule of thumb: in embedded firmware, prefer the caller-owned buffer. It keeps allocation decisions in one place, works inside interrupt handlers and RTOS tasks, and is easy to test.

Common Dangling Pointer in C Strings Mistakes

MistakeWhy it failsFix
Declaring char *p; and passing it to scanfNo storage behind the pointerPoint it at an array or a malloc block
Skipping the field width in %sLong input overflows the bufferUse %15s for a 16 byte buffer
Returning buf from a functionStack frame no longer existsUse a caller buffer, static, or heap
Not checking mallocNULL is used as storageTest the result before using it
Using a pointer after freeMemory may be reusedAssign NULL after freeing

Best Practices, Performance and Security

  • Initialise every pointer when you declare it: to a real object or to NULL.
  • Keep -Wall -Wextra on and read the warnings; -Wreturn-local-addr catches the stack bug above.
  • Run test builds with AddressSanitizer (-fsanitize=address) on your PC to catch wild and dangling accesses early.
  • Always pair a pointer with a length or capacity when you pass it to a function.
  • Prefer fixed buffers over heap allocation in memory constrained embedded C programming.

Performance: avoiding a dangling pointer in C strings also helps speed, since a stack or static buffer costs nothing to allocate, while malloc adds time, fragmentation and failure paths. Security: dangling and wild pointers are exploitable. Attackers can often steer a write through a stale pointer to a location they control, so treat these bugs as vulnerabilities, not just crashes.

Summary and Key Takeaways

  • An array of char * contains addresses, not characters; each address must lead to real storage.
  • A 2-D char array is the simplest safe home for several short strings.
  • malloc per string works, but every block needs a check and a free.
  • Never return the address of a local array: that is the textbook dangling pointer in C strings.
  • A caller-supplied buffer with a size is the most robust pattern for embedded code.

Conclusion

Every dangling pointer in C strings, and every wild one, comes from forgetting where the characters actually live. Whenever you write a pointer to a string, ask two questions: who owns the bytes, and for how long are they valid? If you can answer both, the code is almost always correct. As practice, rewrite the tag builder so it returns a status code and takes the output size, then call it from two places in a loop and confirm the results never overlap. This lecture belongs to our free embedded C course, a free C tutorial for anyone studying C programming for embedded systems, and the next lecture moves on to parsing and recursion.

Frequently Asked Questions

What is a dangling pointer in C strings?

It is a pointer that still holds the address of text whose lifetime has ended, such as a local array of a function that has returned or a heap block that was freed. Using it is undefined behaviour.

What is the difference between a wild pointer and a dangling pointer?

A wild pointer was never initialised, so it holds an arbitrary address. A dangling pointer was valid earlier but its target no longer exists.

Why does scanf into an array of char pointers crash?

The array holds uninitialised addresses, so scanf writes the typed characters to random memory. Give each pointer storage, or use a 2-D char array instead.

Is it safe to return a local array from a function?

No. The array is destroyed when the function returns. Return a pointer to caller-owned, static or heap memory instead.

Which fix is best for embedded systems?

Passing a caller-owned buffer with its size is usually best because it avoids heap use, is re-entrant and makes ownership obvious.

Why did both results print the same text with the static buffer?

A static buffer exists once. The second call overwrote the content written by the first call, so both returned pointers see the latest text.

How can I find these bugs automatically?

Compile with -Wall -Wextra for return-local-addr warnings and run host tests with AddressSanitizer, which reports invalid reads and writes with a stack trace.

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.

<div
💬 Need help or career guidance? Ask us!Contact Us →

2 Comments

Leave a Reply

Your email address will not be published. Required fields are marked *

×

🚀 BLE on Linux (BlueZ)

Hands-on course. Only ₹399

Enroll Now →