Pointers, arrays & memory layout
Use pointers, pointer arithmetic and dynamic allocation without leaks or invalid accesses.
By Invicly Tech, , in Linux System Programming. About 11 minutes to read.
In short
A pointer is a variable that holds a memory address, and nearly every Linux API passes data through pointers to buffers and structs. C gives you manual control over where data lives: on the stack, on the heap with malloc, or in static storage. Understanding this layout is the foundation for every bug you will debug later.
Think of it like this: A pointer is a house address written on paper; copying the paper does not copy the house.
Explained simply
Your computer's memory is like a very long street of numbered boxes. Each box holds one byte, and each box has a number called its address. A normal variable is a box with a value in it. A pointer is a box that holds the address of another box.
Why bother? Because copying big things is slow and sometimes impossible. Instead of handing a function a whole 4 KB buffer, you hand it the address of the buffer. The function can then read or change the original. Almost every Linux call, like read or stat, works this way.
C also makes you decide where data lives. Local variables sit on the stack and vanish when the function returns. Memory from malloc sits on the heap and stays until you call free. Most C bugs come from forgetting which one you are using.
The good news: a handful of simple rules prevent most problems. Check what malloc returns, free each block exactly once, never return the address of a local variable, and set a pointer to NULL after freeing it.
Press Play on a diagram to walk through it one step at a time.
- 1Stack
Local variables and return addresses; grows down.
- 2Memory mappings
Shared libraries and mmap regions.
- 3Heap
malloc and free; grows up.
- 4BSS
Globals and statics initialised to zero.
- 5Data
Globals and statics with initial values.
- 6Text
Read-only machine code.
- 1Declare
int *buf = NULL;
- 2Allocate
buf = malloc(n * sizeof *buf);
- 3Check
if (!buf) handle the error
- 4Use
Only indexes 0 to n - 1
- 5Free
free(buf); buf = NULL;
In depth
What the * and & symbols really do
The & operator asks "where does this live?" and gives you an address. The * operator goes the other way: "go to this address and use what is there". So if int x = 7 and int *p = &x, then *p is 7, and writing *p = 9 changes x itself.
The type of a pointer matters. An int * tells the compiler that the box at that address holds an int, so *p reads 4 bytes (on Linux x86-64) and p + 1 moves forward by 4 bytes, not 1. A char * moves by 1 byte. A void * is a pointer with no type: you can store any address in it, but you must convert it to a real pointer type before using the data.
- &x gives the address of x
- *p reads or writes the value at p
- p + 1 moves by sizeof(*p) bytes
- void * holds any address but cannot be dereferenced
Stack, heap and static data in practice
The stack is fast and automatic. Each function call gets a frame for its locals, and the frame disappears on return. It is small, usually 8 MB for the main thread, so huge local arrays can overflow it.
The heap is for data whose size you only know at run time, or that must outlive the function that made it. You ask for it with malloc or calloc and give it back with free. Forget free and you leak; free twice and you corrupt the allocator.
Static storage holds globals and static locals. It exists for the whole run of the program and starts as zero unless you give a value.
- Stack: automatic, small, gone on return
- Heap: manual, large, lives until free
- Static: whole program lifetime, zero by default
Passing pointers so a function can change your data
C passes every argument by value, which means the function gets a copy. If you pass an int, changing it inside the function does nothing outside. To let a function change your variable, pass its address instead.
This is how many Linux APIs return more than one result. For example, stat fills in a struct stat that you own: you pass &st and the kernel writes into it. The same pattern appears with a pointer to a pointer. A function that allocates memory for you, such as getline, takes a char ** so it can update your char * to point at a new, bigger buffer.
- f gets a copy of x
- Changes stay inside f
- x is unchanged after the call
- f gets a pointer p to x
- *p = 9 writes into x
- x is changed after the call
The bugs to watch for
A dangling pointer points at memory that is no longer yours: a freed heap block or a stack frame that has returned. Using it may seem to work, then break later in a confusing way.
An out-of-bounds access reads or writes past the end of an array. C does not check this. A buffer of 10 ints has valid indexes 0 to 9, and a[10] silently touches whatever sits next door.
A leak is heap memory you can no longer reach because you lost the last pointer to it. Short programs survive leaks, but long-running servers slowly run out of memory.
- Set pointers to NULL after free
- Use sizeof *p in malloc so the size follows the type
- Keep an explicit length next to every buffer
- Dangling pointer
- Points at a freed block
- Or at a returned stack frame
- Out of bounds
- a[10] in a 10-int array
- C does not check
- Leak
- Last pointer to a block lost
- Double free
- Corrupts the allocator
Learn it in 5 short steps
About 1h each. Track them with a timer in your plan.
- 1Declare and dereference pointers~1h
- 2Relate arrays and pointer arithmetic~1h
- 3Allocate and free heap memory~1h
- 4Distinguish stack, heap and static data~1h
- 5Pass pointers to modify caller data~1h
Key points
- p holds an address; *p reads or writes the value stored at that address.
- An array name decays to a pointer to its first element, so a[i] equals *(a + i).
- Pointer arithmetic moves in units of the pointed-to type, not bytes.
- Every malloc needs exactly one matching free, and a pointer to a local variable is invalid after the function returns.
Key terms
Tap a card to flip it. 0/6 known
Examples
#include <stdio.h>
#include <stdlib.h>
void fill(int *a, size_t n) {
for (size_t i = 0; i < n; i++) a[i] = (int)(i * i);
}
int main(void) {
size_t n = 5;
int *a = malloc(n * sizeof *a);
if (!a) { perror("malloc"); return 1; }
fill(a, n);
printf("a[3] = %d\n", a[3]);
free(a);
return 0;
}Allocate an array on the heap, fill it through a pointer, then free it.
Swapping two numbers through pointers
A swap function must change the caller's variables, so it takes their addresses. Inside, *a and *b are the caller's real boxes. We copy one value into a temporary, then move the values across. After the call, x and y in main have traded places. If swap took plain ints instead, it would only swap its own copies.
#include <stdio.h>
static void swap(int *a, int *b) {
int tmp = *a;
*a = *b;
*b = tmp;
}
int main(void) {
int x = 1, y = 2;
swap(&x, &y);
printf("x=%d y=%d\n", x, y); /* x=2 y=1 */
return 0;
}Growing a buffer safely with realloc
Say you read numbers but do not know how many will come. Start with room for 4, and double the capacity whenever it fills. The key detail is to store realloc's result in a temporary pointer first. If realloc fails it returns NULL but leaves the old block alive, so assigning straight to buf would leak it. Only after the check do we update buf and cap. It prints len=100 cap=128.
#include <stdio.h>
#include <stdlib.h>
int main(void) {
size_t cap = 4, len = 0;
int *buf = malloc(cap * sizeof *buf);
if (!buf) { perror("malloc"); return 1; }
for (int v = 0; v < 100; v++) {
if (len == cap) {
int *tmp = realloc(buf, 2 * cap * sizeof *buf);
if (!tmp) { perror("realloc"); free(buf); return 1; }
buf = tmp; cap *= 2;
}
buf[len++] = v;
}
printf("len=%zu cap=%zu\n", len, cap); free(buf); return 0; }Quick reference
- int *p = &x; then *p is x
- a[i] is exactly *(a + i)
- malloc(n * sizeof *p) keeps the size tied to the pointer's type
- calloc(n, size) gives zeroed memory and checks n * size for overflow
- Always check malloc and realloc for NULL
- Assign realloc to a temporary pointer, then swap it in
- free(NULL) is safe and does nothing
- Never return the address of a local variable
Common mistakes
- Using memory after free or freeing it twice.
- Forgetting sizeof when computing allocation sizes.
Quick quiz
Pick an answer to see if you're right and why.
Practice exercises
Try each one yourself first. Use the hint if you get stuck, then compare with the solution.
- Exercise 1easy
Write a function sum(const int *a, size_t n) that returns the total of n ints, and call it on a stack array of 5 numbers.
- Exercise 2medium
Write char *dup_str(const char *s) that returns a heap copy of s, like strdup. The caller frees it. Handle allocation failure.
- Exercise 3hard
Find and explain the bug: char *greet(void) { char msg[32]; snprintf(msg, sizeof msg, "hi"); return msg; } Then give two correct ways to fix it.
Check yourself
Answer in your head, reveal, then be honest with yourself.
Feel confident about this topic?
Frequently asked questions
- What is the difference between NULL and an uninitialised pointer?
- NULL is a known value meaning "points to nothing", and you can test for it. An uninitialised pointer holds random garbage, so using it can touch any memory. Always initialise pointers, even if only to NULL.
- Do I need to cast the result of malloc in C?
- No. In C a void * converts to any object pointer type automatically, and adding a cast can hide a missing #include of stdlib.h. The cast is only needed in C++.
- Why does my program work even though I read past the end of an array?
- C does not check bounds, so the read just returns whatever bytes are next in memory. It is still undefined behaviour and may crash or corrupt data later. AddressSanitizer will catch it immediately.