🚀 Learn BLE on Linux (BlueZ) – Programming Part 1
Hands-on Bluetooth Low Energy course. Special price: ₹399
Enroll Now on Udemy →Return Structure Pointer Safely
Free C Programming Course for Embedded Systems · Structure and Union · Lecture 19
Returning a structure copies it. Returning a pointer to a structure from a function in C copies only an address, which is fast, but it raises a question that the earlier lectures did not have: who owns the memory the pointer points to? In this lecture of our free C programming course we answer that question with three safe patterns and one famous bug.
The topic is central to embedded C programming, where you must decide between heap allocation, static storage and caller-supplied buffers. Many free embedded C course students first meet the dangling pointer here.
Table of Contents
What You Will Learn
After this lecture you can:
- Return a pointer to a heap-allocated structure and free it correctly.
- Explain why returning the address of a local structure is a bug.
- Write the caller-supplies-storage pattern that avoids malloc.
- Check for NULL after allocation and handle failure.
- Choose a pattern that suits a microcontroller with no or limited heap.
Prerequisites
You need pointers to structures (lecture 17), the arrow operator, and a first look at malloc and free from the Pointers chapter of this free C tutorial.
The Rule: Where Does the Object Live?
A pointer is only useful while the object it points to still exists. So before you return a pointer, ask where the object lives and how long it will live.
| Storage | Lifetime | Safe to return its address? |
|---|---|---|
| Local (automatic) variable | Until the function returns | No |
| static local or global | Whole program | Yes, but shared by all callers |
| Heap via malloc | Until free is called | Yes, caller must free |
| Caller’s own variable | Caller decides | Yes, the caller already owns it |
Pattern 1: Allocate with malloc
The function allocates a structure, fills it, and returns the pointer. The caller owns the object from then on and must release it. A matching destroy function keeps the pairing obvious. Notice the NULL check: malloc can fail, and on a small device it will, sooner than you expect.
Heap object handed to the caller
Pattern 2: Caller Supplies the Storage
Many firmware projects forbid the heap entirely, because fragmentation and allocation failure are hard to reason about. The alternative is an init function. The caller declares the structure wherever it likes (stack, static, a memory pool) and passes its address. The function fills it in and returns a status. No ownership transfer, no free.
#define _POSIX_C_SOURCE 200809L
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct frame {
unsigned id;
unsigned len;
unsigned char data[8];
};
static struct frame *frame_create(unsigned id, const char *text)
{
struct frame *f = malloc(sizeof *f);
if (f == NULL)
return NULL;
memset(f, 0, sizeof *f);
f->id = id;
f->len = (unsigned)strnlen(text, sizeof f->data);
memcpy(f->data, text, f->len);
return f;
}
static void frame_destroy(struct frame *f)
{
free(f);
}
/* Embedded-friendly variant: caller owns the storage. */
static int frame_init(struct frame *f, unsigned id, const char *text)
{
if (f == NULL)
return -1;
memset(f, 0, sizeof *f);
f->id = id;
f->len = (unsigned)strnlen(text, sizeof f->data);
memcpy(f->data, text, f->len);
return 0;
}
static void frame_print(const struct frame *f)
{
printf("frame id=0x%X len=%u data=%.*s\n", f->id, f->len,
(int)f->len, (const char *)f->data);
}
int main(void)
{
struct frame *heap_f = frame_create(0x1A, "HELLO");
if (heap_f == NULL) {
puts("out of memory");
return 1;
}
frame_print(heap_f);
frame_destroy(heap_f);
heap_f = NULL;
struct frame stack_f;
if (frame_init(&stack_f, 0x2B, "WORLD") == 0)
frame_print(&stack_f);
return 0;
}
Build and run:
gcc -std=c11 -Wall -Wextra -o ret_ptr ret_ptr.c
./ret_ptr
Expected output:
frame id=0x1A len=5 data=HELLO
frame id=0x2B len=5 data=WORLD
Why the demo uses memset and a length
The data array holds raw bytes, not a C string, so we keep an explicit len and print with a precision. Clearing the whole structure first guarantees no stale bytes leak into the unused part of the buffer. After free we set the pointer to NULL so a later accidental use fails loudly instead of corrupting memory.
The Dangling Pointer Bug
Here is the mistake that gives this topic its reputation. A function declares a local structure, fills it, and returns &local. The code compiles, sometimes with only a warning. But when the function returns, its stack frame is released, and the pointer now refers to memory that will be reused by the very next call. The caller reads garbage, or worse, writes over somebody else’s variables.
Dangling pointer from a local variable
Warning: a dangling pointer often appears to work in a quick test, because the old bytes have not yet been overwritten. That makes the bug intermittent and very hard to debug. Enable -Wall; GCC warns about returning the address of a local variable.
The static Shortcut and Its Cost
Declaring the local as static keeps it alive, so returning its address is legal. The price is that every call returns the same object, so a second call overwrites the first result, and the function is not safe to call from two tasks at once. Use this only for simple, single-threaded utilities and document it.
Choosing a Pattern for Embedded Targets
| Pattern | Heap needed | Reentrant | Best for |
|---|---|---|---|
| malloc and free | Yes | Yes | Linux userspace, hosted C |
| Caller supplies storage | No | Yes | Bare-metal and RTOS drivers |
| static internal object | No | No | Tiny single-task helpers |
| Return by value | No | Yes | Small results |
Common Mistakes
| Mistake | Consequence | Fix |
|---|---|---|
| Returning the address of a local structure | Dangling pointer | Use heap, caller storage or static |
| Not checking malloc for NULL | Crash on first use | Test and handle failure |
| Forgetting to free | Memory leak, fatal on small RAM | Pair every create with a destroy |
| Freeing twice | Heap corruption | Set pointer to NULL after free |
| Using a pointer after free | Undefined behaviour | NULL it and never touch it again |
Best Practices
- Decide ownership up front and write it in the function comment.
- Name allocate and release functions as a pair, such as create and destroy.
- Prefer caller-supplied storage in firmware; reserve malloc for hosted environments.
- Run your PC-side tests under a memory checker such as Valgrind or AddressSanitizer.
- Set freed pointers to NULL immediately.
Summary and Conclusion
Key Takeaways
- A returned pointer is valid only if the object outlives the function.
- Never return the address of an automatic local variable.
- Heap objects need a matching free; check malloc for NULL.
- On embedded targets, caller-supplied storage is usually the safest design.
Returning a pointer to a structure from a function in C is powerful, and now you know the rules that keep it safe. In the final lecture of this chapter section we pass an array of structures to a function, review everything with a quiz, and finish with interview questions.
Suggested Images
- Diagram comparing heap, stack and static storage lifetimes. ALT: return pointer to structure from function in C memory lifetimes, free C programming course
- Illustration of a dangling pointer after a stack frame is released. ALT: embedded C programming dangling pointer return local structure, free embedded C course
Frequently Asked Questions
Can I return a pointer to a local structure in C?
No. The local is destroyed on return, so the pointer dangles.
Who frees a structure returned by a create function?
The caller, using the matching destroy or free function.
How do I avoid malloc in embedded C?
Let the caller supply the structure and pass its address to an init function.
What does a static local structure change?
It lives for the whole program so its address stays valid, but all calls share one object.
Why set a pointer to NULL after free?
It prevents accidental reuse and makes a second free harmless.
Does GCC warn about returning a local address?
Yes, with -Wall it normally reports it, which is one more reason to compile with warnings on.
Almost Done with This Chapter Section
The next lecture covers arrays of structures and ends with a quiz and interview questions in this free embedded C course.

2 Comments