Why pointers exist
3 min readComputer memory is a long sequence of bytes, and every byte has an integer number called its the number of a byte in memory, counting up from zero, that identifies where that byte is stored. The first byte sits at some low address, the next at the next address, and so on. A value that occupies several bytes, such as an int, is stored in a run of adjacent bytes, and its address is the address of its first byte.
A a variable that holds an address, so it tells you where another object lives rather than holding the object's value is simply a variable that stores one of these addresses. Where an int variable holds a number such as 10, a pointer variable holds an address such as the location of that 10. The pointer is not the value, just as a street address is not the house, but it names where the value lives.
Pointers exist for four concrete reasons a systems programmer meets constantly. First, they let a function modify a caller's variable or return more than one result, because passing an address lets the function write through it. Second, arrays are blocks of memory and C deals with them through a pointer to their first element, which is also why arrays are cheap to pass around: you hand over one address rather than a copy of every element. Third, dynamic memory, the heap you will meet in a later session, gives you a block of memory and hands back its address, so a pointer is the only way to name it. Fourth, and most important for embedded work, hardware is accessed by address: a peripheral register is a fixed location in the memory map, and a driver writes to it by making a pointer to that address and storing through it.
On an ARM board a device such as a UART has its registers at fixed addresses chosen by the chip vendor. A driver reaches one by declaring a pointer to that address and writing through it, for example a volatile uint32_t *reg = (volatile uint32_t *)0x40010000; followed by *reg = 0x01;. The C language has no special register syntax for this: writing to hardware is just writing through a pointer to a known address, which is why pointers are the central tool of systems programming. The volatile qualifier and the memory-management unit that maps those physical addresses into your program are covered in later modules.
Addresses and declaring pointers
5 min readTo get the address of a variable you use the address-of operator, &. Applied to an int named i, the expression &i is a pointer to i, and its type is int *, read as "pointer to int". You print an address with the %p conversion, and because %p expects a void *, the tidy form casts the pointer:
#include <stdio.h>
int main(void)
{
int i = 10;
printf("value %d at address %p\n", i, (void *)&i);
return 0;
}
A pointer is declared by writing * in front of the variable name:
int i;
int *p; /* p has type int *, pointer to int */
p = &i; /* p now holds the address of i */
The * here is part of the declarator, not an operator, and it is not a dereference. This distinction is the source of one of C's oldest traps. The statement int *p, q; declares p as a pointer to int but q as a plain int, because the * applies only to the name that follows it. Writing int* p, q; does not change this, the spacing is irrelevant, so the pointer type and the name q are separate things. To declare two pointers write int *p, *q;. To read a declaration reliably, start from the variable name and work outward: int *p means "p is a pointer to an int".
A pointer that currently points at nothing holds the special value the special pointer value that points at nothing, used to say a pointer is currently unassigned or empty, written NULL. NULL is defined in <stddef.h>, which also provides size_t and, later in this lesson, ptrdiff_t. It is a null pointer constant, typically ((void *)0) or plain 0, that converts to a null pointer of whatever pointer type you assign it to.
#include <stddef.h>
int *p = NULL; /* p points at nothing for now */
NULL is not the same as the character '\0', the null byte that ends a string, even though both are spelled with a zero. Comparing a pointer against NULL asks whether the pointer points at anything, while comparing a character against '\0' asks about the byte the pointer points at. Dereferencing a null pointer, reading or writing *p when p is NULL, is undefined behaviour and, on Linux, usually ends the program with a segmentation fault.
The size of a pointer is the size of an address, not the size of the thing it points at. On 64-bit Linux sizeof(int *) is 8 while sizeof(int) is 4; on a 32-bit ARM microcontroller both an int and a pointer are 4 bytes. Because sizeof works on the type of its operand, sizeof p is the size of the pointer, while sizeof *p is the size of the pointed-to int, and *p is not evaluated, so this is safe even when p is NULL.
Going deeperNULL is a null pointer constant, not a memory address
The standard defines NULL as a null pointer constant: an integer constant expression with value 0, or such an expression cast to void *. Implementations therefore define it as 0, 0L or ((void *)0). Comparing a pointer to NULL always compares against the null pointer value regardless of how NULL is spelled, and on every mainstream system the null pointer has the numeric value zero, so a pointer that reads 0x0 in gdb is the null pointer. This is why an uninitialised pointer is so dangerous: it is not NULL, it is an indeterminate address, so it fails the NULL test yet still points nowhere valid. Some embedded code writes (void *)0 explicitly rather than rely on the header, and a few very old ABIs used a non-zero null pointer, which is why the standard refuses to promise that the null pointer is address zero.
int main(void)
{
int i = 10;
int j = 20;
printf("i = %d at %p\n", i, (void *)&i);
printf("j = %d at %p\n", j, (void *)&j);
printf("sizeof(int) = %zu, sizeof(int *) = %zu\n", sizeof(int), sizeof(int *));
return 0;
}
learner@embeddex:~/lab$ # compile it
learner@embeddex:~/lab$ gcc -o addr addr.c
learner@embeddex:~/lab$ # each variable has its own address, a large virtual address; an int is
4 bytes but a pointer is 8 on 64-bit
learner@embeddex:~/lab$ ./addr
i = 10 at 0x7ffdb169de40
j = 20 at 0x7ffdb169de44
sizeof(int) = 4, sizeof(int *) = 8
learner@embeddex:~/lab$ # run it again: the address changes between runs because the OS randomis
es the stack
learner@embeddex:~/lab$ ./addr
i = 10 at 0x7fff161428d0
j = 20 at 0x7fff161428d4
sizeof(int) = 4, sizeof(int *) = 8Dereferencing and the swap-by-pointer pattern
4 min readThe indirection operator, *, is the inverse of &. If p holds the address of i, then *p is i, the object itself. This is called following a pointer to read or write the object at the address the pointer holds, written with the unary * operator. The same character appears in the declaration int *p and in the multiplication a * b, but only the one used as a unary prefix operator on a pointer is a dereference.
int i = 10;
int *p = &i;
printf("%d\n", *p); /* reads i, prints 10 */
*p = 20; /* writes i, which is now 20 */
printf("%d\n", i); /* prints 20 */
Because & and * are inverses, &*p is the same as p, and *&i is the same as i. Taking the address and then dereferencing, in either order, lands you back where you started.
The reason pointers matter for functions is that C passes arguments by value, and a pointer is a value too. When you pass a pointer to a function, the function receives a copy of the pointer, but that copy still holds the same address, so dereferencing it reaches the caller's original object. This is how a function finally changes a caller's variable, the thing increment in the last lesson could not do:
void increment(int *p)
{
*p = *p + 1; /* add one to the object p points at */
}
int main(void)
{
int i = 10;
increment(&i); /* pass the address of i */
printf("%d\n", i); /* prints 11 */
return 0;
}
The classic application is a swap function. You cannot swap two ints by passing the ints themselves, because the function would only swap its copies. You swap by passing their addresses:
void swap(int *a, int *b)
{
int tmp = *a;
*a = *b;
*b = tmp;
}
int main(void)
{
int x = 3, y = 7;
swap(&x, &y);
printf("%d %d\n", x, y); /* 7 3 */
return 0;
}
Pass the addresses: the caller evaluates &x and &y, and copies those addresses into the parameters a and b.
Copy into parameters: a holds the address of x and b holds the address of y, so *a names x and *b names y.
**Save *a**: tmp = *a stores the value of x, 3, in a local variable.
**Move *b into *a**: *a = *b writes the value of y, 7, into x, so x becomes 7.
Restore the saved value: *b = tmp writes 3 into y, and the two values are now exchanged.
A function can also hand back several results at once using out-parameters. A function that needs to return both a quotient and a remainder, or a value and an error flag, cannot do it with a single return, so it takes pointers to the places the caller wants the results written:
int divide(int a, int b, int *quot, int *rem)
{
if (b == 0)
return -1; /* signal failure */
*quot = a / b; /* write both results */
*rem = a % b;
return 0; /* success */
}
A function cannot change which variable the caller's pointer points at by reassigning its parameter, because the parameter is a copy of the pointer. Reassigning the parameter inside the function changes only the copy. To let a function change the caller's pointer itself, you need a pointer to the pointer, the subject of a later section.
learner@embeddex:~/lab$ # one swap takes the ints, the other takes their addresses
learner@embeddex:~/lab$ cat swap.c
#include <stdio.h>
void swap_val(int a, int b) { int t = a; a = b; b = t; }
void swap(int *a, int *b) { int t = *a; *a = *b; *b = t; }
int main(void)
{
int x = 3, y = 7;
swap_val(x, y);
printf("after by-value swap: %d %d\n", x, y);
swap(&x, &y);
printf("after by-pointer swap: %d %d\n", x, y);
return 0;
}
learner@embeddex:~/lab$ # compile it
learner@embeddex:~/lab$ gcc -o swap swap.c
learner@embeddex:~/lab$ # passing the ints swaps only copies; passing &x and &y writes through t
o the caller's variables
learner@embeddex:~/lab$ ./swap
after by-value swap: 3 7
after by-pointer swap: 7 3Pointer arithmetic
4 min readadding or subtracting an integer to a pointer, where the pointer advances by that many elements of the pointed-to type rather than that many bytes is the operation that turns a pointer into a way of walking over a block of memory. If p points at an int, then p + 1 points at the next int in memory, and p + n points n ints ahead. The compiler scales the offset by sizeof(*p), so in bytes p + n advances n * sizeof(*p) bytes:
int a[5] = {11, 22, 33, 44, 55};
int *p = &a[0]; /* or simply p = a */
printf("%d\n", *p); /* 11 */
printf("%d\n", *(p + 1)); /* 22, one int later */
printf("%d\n", *(p + 3)); /* 44, three ints later */
Because scaling is automatic, you never multiply by sizeof(int) yourself. If p were a double *, then p + 1 would advance by sizeof(double), typically 8 bytes, and the same code would still read the next element. This is the entire point: the code reads correctly for any pointed-to type.
The pointer itself can also move. The increment and decrement operators p++ and p-- move p one element forward or back, and are the idiomatic way to walk a buffer:
int a[] = {11, 22, 33, 44, 55, 0};
int *p = &a[0];
while (*p != 0) { /* walk until the sentinel */
printf("%d\n", *p);
p++; /* advance one int */
}
Subtracting one pointer from another gives the number of elements between them, not the number of bytes. The result has type a signed integer type from stddef.h used to hold the difference of two pointers, measured in elements, and it is well defined only when both pointers point into the same array. A pointer version of strlen uses exactly this:
size_t my_strlen(const char *s)
{
const char *p = s;
while (*p != '\0')
p++;
return (size_t)(p - s); /* count of characters */
}
Pointers into the same array can also be compared with the relational operators <, <=, > and >=, so a loop can test p < end instead of using a sentinel. One special pointer is the one-past-the-end pointer, the address just after the last element of an array: a + 5 for a five-element array. You may form it and compare against it, but reading or writing *(a + 5) is undefined behaviour.
Take the type: the compiler looks at the pointed-to type of p, say int.
Measure one element: it reads sizeof(*p), the size of one int.
Scale the offset: it multiplies the integer n by that size, giving the byte offset.
Add the bytes: it adds the byte offset to the address held in p.
Produce a pointer: the result is a pointer of the same type, n elements further along.
Pointer arithmetic is defined only while you stay inside one array, or one element past its end. Forming a pointer that lands outside that range, by a wild subtraction or a loop that runs too far, is undefined behaviour even if you never dereference it. This is the rule that makes pointer bugs so dangerous: the mistake may not crash immediately.
int main(void)
{
int a[] = {11, 22, 33, 44, 55, 0};
int *p = a;
printf("*(p+1) = %d, *(p+3) = %d\n", *(p + 1), *(p + 3));
printf("walk with p++: ");
while (*p != 0) { printf("%d ", *p); p++; }
printf("\n");
printf("indexed access: ");
for (int k = 0; k < 5; k++) printf("%d ", a[k]);
printf("\n");
printf("p - a = %td elements\n", p - a);
return 0;
}
learner@embeddex:~/lab$ # compile it
learner@embeddex:~/lab$ gcc -o arith arith.c
learner@embeddex:~/lab$ # the p++ walk and indexed access print identical values; p - a counts 5
elements
learner@embeddex:~/lab$ ./arith
*(p+1) = 22, *(p+3) = 44
walk with p++: 11 22 33 44 55
indexed access: 11 22 33 44 55
p - a = 5 elementsconst and pointers
3 min readIn the last lesson const guarded a scalar parameter. With pointers it can guard two different things, and the position of the keyword tells them apart. There are three forms:
const int *p; /* pointer to const int: cannot write *p */
int *const p; /* const pointer: cannot reassign p */
const int *const p; /* both: cannot write *p, cannot reassign p */
The first, const int *p, means p points at an int you promise not to modify. You can read *p, and you can point p at another int, but you cannot write through it, and the compiler rejects any attempt. This is the form to use for a function that inspects but must not change its argument, which is exactly how my_strlen above declared its parameter const char *s.
The second, int *const p, means the pointer itself is fixed. You can write *p freely, but you cannot make p point elsewhere, so p++ is a compile-time error. The third combines both.
The clean way to read any of these is right to left. Start at the variable name and read outward, crossing the * symbols in order: const int *p reads "p is a pointer to an int that is const", and int *const p reads "p is a const pointer to an int". const protects whatever is immediately to its right when read that way: in const int *p the const sits before the int, protecting the int; in int *const p it sits before the p, protecting the pointer.
The compiler is strict about this because removing const silently would let a program break its own promise. Assigning a const int * to an int * discards the qualifier and is a constraint violation, so the compiler must diagnose it (gcc reports "discards const qualifier"), because the new pointer could then modify the supposedly constant object:
const int n = 100;
int *p = &n; /* error: discards const, could write through p */
The pointer-to-const declaration is also how the standard library advertises its guarantees. strlen is declared size_t strlen(const char *s);, which promises the function will not modify your string and lets it accept both writable and read-only strings, including string literals.
Pointers to pointers
4 min readBecause a pointer is just a variable holding an address, it too lives at some address, and you can take the address of it with &. The result is a a pointer whose value is the address of another pointer, written int ** or char **, used when code must change or pass around a pointer itself:
int x = 3490;
int *p = &x; /* p points at x */
int **q = &p; /* q points at p */
printf("%d\n", **q); /* follow q, then follow p: 3490 */
Each & adds one level of indirection, and each * removes one. &x has type int *, &p has type int **, and **q unwinds both levels back to the int. The type spells it out: int **q means "q is a pointer to a pointer to an int".
A pointer to a pointer exists for three concrete reasons. The first is the command-line arguments to main, which the next lesson develops. The second parameter of int main(int argc, char **argv) is a char **, a pointer to an array of char * strings, which is how a program receives a list of text arguments whose length varies at run time. The second reason is an out-parameter that sets a caller's pointer. If a function must give back a pointer, for example to return a newly allocated buffer or a found node, the caller passes the address of its own pointer and the function writes through it:
int find_target(int **out)
{
static int target = 42;
*out = ⌖ /* write the caller's pointer */
return 0;
}
The third reason is arrays of strings, a table of text where each row is itself a pointer to a char array. A function that takes an array of strings is written with a char ** parameter precisely because the array decays to a pointer to its first element, and that first element is itself a char *, giving a pointer to a pointer.
The const rules compose the same way. int *const *q means "q is a pointer to a const pointer to an int": you may move q and read the final int, but you may not modify the intermediate pointer that q points at. Getting these levels right is a matter of applying the right-to-left reading twice.
When a double pointer confuses you, count the stars. q is int **, *q is int * (the pointer p), and **q is int (the value x). Each dereference peels off one level of indirection and changes the type accordingly.
learner@embeddex:~/lab$ # q is int **: it holds the address of p, and **q unwinds both levels
learner@embeddex:~/lab$ cat ptrptr.c
#include <stdio.h>
int main(int argc, char **argv)
{
int x = 3490;
int *p = &x;
int **q = &p;
printf("**q = %d (q -> p -> x)\n", **q);
printf("argc = %d, argv[1] = %s\n", argc, argv[1]);
return 0;
}
learner@embeddex:~/lab$ # compile it
learner@embeddex:~/lab$ gcc -o ptrptr ptrptr.c
learner@embeddex:~/lab$ # argv is char **, a pointer to an array of strings; argv[1] is the firs
t argument
learner@embeddex:~/lab$ ./ptrptr hello
**q = 3490 (q -> p -> x)
argc = 2, argv[1] = hellovoid* and storing addresses as integers
3 min readA a pointer declared void * that holds an address without stating what type of object is stored there, void *, is the generic pointer type. It says "this is an address" and deliberately says nothing about what is at that address. C allows an object pointer of any type to be converted to void * and back implicitly, with no cast, and the round trip is guaranteed to give back the original pointer.
int i = 5;
void *vp = &i; /* implicit: any pointer to void * */
int *ip = vp; /* implicit: void * back to int * */
Because void * carries no type, you cannot dereference it, cannot index it, and cannot do pointer arithmetic on it in standard C, since all of those need to know the size of one element. It exists to build one function that handles many types. memcpy copies bytes between any two objects and is declared with void * parameters precisely so it does not care what the objects are:
void *memcpy(void *dest, const void *src, size_t n);
Likewise qsort sorts an array of anything by receiving the array's base as a void *, its element size as a size_t, and a comparison function that receives two const void *:
void qsort(void *base, size_t nmemb, size_t size,
int (*compar)(const void *, const void *));
Inside such a function you convert the void * to a real pointer before touching the data. A hand-written byte copy is the classic pattern:
void *my_memcpy(void *dest, const void *src, size_t n)
{
const unsigned char *s = src; /* void * to unsigned char * */
unsigned char *d = dest;
while (n-- > 0)
*d++ = *s++; /* copy one byte at a time */
return dest;
}
There is one deliberate asymmetry between C and C++. In C the conversions in both directions are implicit; in C++ you may convert a typed pointer to void * implicitly, but converting void * back to a typed pointer requires an explicit cast. Code written as portable C, or a C library wrapped for C++, has to be aware of this. In C a cast here is harmless and sometimes added for clarity.
Sometimes you must treat an address as a number, to print it, hash it, or store it in a table alongside integers. For that C provides the optional integer types intptr_t and uintptr_t in <stdint.h>, wide enough to hold any pointer on the platform. Converting a pointer to uintptr_t and back to a pointer is guaranteed to reproduce the original pointer:
#include <stdint.h>
int i = 5;
int *p = &i;
uintptr_t n = (uintptr_t)p; /* address as an integer */
int *q = (int *)n; /* and back again */
No other pointer-to-integer conversion carries that guarantee. On an embedded system this is occasionally used to pass an address through a message queue or a hardware interface that only carries integers, though in most drivers a void * or a fixed-address pointer is clearer.
A common bug is to add 1 to a void * and expect it to advance one element. That arithmetic is a GNU extension that treats void * as char *, and it is non-standard: portable code must cast to a typed pointer, usually unsigned char *, before doing any arithmetic. You cannot know how far one element is until you know the element type.
The memory model, endianness, and gdb x
5 min readThe memory model behind everything in this lesson is simple: memory is a byte array, every object occupies a run of bytes, and a pointer names the first byte of that run. What you have not yet had to know is the order in which the bytes of a multi-byte value are laid out, called the order in which the bytes of a multi-byte value are stored in memory, most-significant first or least-significant first.
In little-endian order, used by x86 and by ARM in its normal configuration, the least significant byte is stored at the lowest address, so the value 0x12345678 is laid out in memory as 78 56 34 12 reading from the lowest address upward. In big-endian order, used by some older and network-oriented machines, the bytes appear in the familiar order 12 34 56 78. The formal rules for producing and reading a specific byte order are covered in the bit-manipulation session; here the goal is to see the layout with your own eyes.
gdb's examine command, x, prints raw memory in a chosen format, independent of your program's types. Its general form is x/nfu addr, where n is a repeat count, f is a format letter (x for hexadecimal, d for decimal, s for a string, c for characters, a for an address, i for instructions), and u is a unit size (b for byte, h for halfword, w for word, g for giant word). To see the four bytes of an int one at a time, stop the program in gdb and type x/4xb &i, four units, hexadecimal, bytes, starting at the address of i. The output is the well-known standard form; a typical result, with your addresses and values differing, is:
(gdb) x/4xb &i
0x7fffffffe29c: 0x78 0x56 0x34 0x12
The four bytes read 78 56 34 12, the little-endian layout of 0x12345678, which confirms that the least significant byte 0x78 sits at the lowest address. This is the third lab exercise for this session. The same command can walk a whole array or dump a region of memory in decimal with x/10dw p, or show a null-terminated string with x/s p. Each time you use x, its count, format and unit become the new defaults, so a later x/20 after x/4xb means "20 bytes in hex".
Going deeperWhy your addresses are huge: virtual memory
The addresses printed by %p and shown by gdb on a desktop, values like 0x7fffffffe29c, are virtual addresses, not physical ones. The memory-management unit translates each virtual address to a physical address on every access, so every process gets its own private address space and can use addresses far larger than the physical RAM installed. The huge-looking stack address is normal and says nothing about how much memory you have. Address space layout randomisation even changes the location of the stack and heap between runs, which is why the exact numbers differ each time and why you must never hard-code or persist an address from one run to the next. On a small embedded board without an MMU, or in bare-metal firmware, the situation is reversed: addresses are physical, the range is small, and a pointer value means exactly the byte it names in the device's address map, which is what makes the register-access idiom in the first section work.
learner@embeddex:~/lab$ # i holds 0x12345678; we will look at its four raw bytes in memory
learner@embeddex:~/lab$ cat endian.c
#include <stdio.h>
int main(void)
{
int i = 0x12345678;
char s[] = "hello";
printf("i = 0x%x, s = %s\n", i, s);
return 0;
}
learner@embeddex:~/lab$ # compile with -g so gdb can name i and s
learner@embeddex:~/lab$ gcc -g -o endian endian.c
learner@embeddex:~/lab$ # run it normally: i prints as 0x12345678
learner@embeddex:~/lab$ ./endian
i = 0x12345678, s = hello
learner@embeddex:~/lab$ # x/4xb dumps four bytes in hex: 78 56 34 12, least significant byte at
the lowest address
learner@embeddex:~/lab$ gdb -q -batch -ex 'break 6' -ex 'run' -ex 'x/4xb &i' ./endian
bash: gdb: command not found
learner@embeddex:~/lab$ # x/1dw reads it as one decimal word, and x/s prints the string at s
learner@embeddex:~/lab$ gdb -q -batch -ex 'break 6' -ex 'run' -ex 'x/1dw &i' -ex 'x/s s' ./endia
n
bash: gdb: command not foundAlignment: why addresses are multiples of a size
4 min readEvery object type has an the requirement that an object's address be a multiple of some power of two, usually its size, which the compiler and allocator must satisfy requirement. On mainstream platforms an int is aligned to 4 bytes and a double to 8, which normally means their addresses are multiples of 4 and 8. The compiler satisfies this automatically for variables, struct fields and arrays by inserting padding where needed, and you can query a type's alignment with the _Alignof operator or the alignof macro in <stdalign.h>:
printf("%zu %zu\n", _Alignof(int), _Alignof(double));
Alignment matters because hardware reads memory in fixed chunks. A load that crosses an alignment boundary may require two memory transactions instead of one, and on some machines it is simply not supported. C itself calls reading through a misaligned pointer undefined behaviour, regardless of what the hardware does. x86 tolerates misaligned loads and stores, at a small performance cost. Other architectures, including several ARM configurations, fault on misaligned access. An embedded developer porting code to a new board often meets this the hard way: a structure that packed fields tightly on x86 crashes or produces wrong data on an ARM target until the fields are realigned. The bit-manipulation session covers packed structs and how to read an unaligned value explicitly and portably.
The reason malloc is safe for any type is that it returns memory suitably aligned for any object type with a fundamental alignment. That guarantee is part of its contract, so a pointer returned by malloc can hold a double or a struct without special handling. The same is not automatically true of memory you carve out of a byte buffer yourself: a pointer into the middle of a char array has only byte alignment, and casting it to an int * and dereferencing it is a latent misaligned-access bug.
Going deeperWhy sizeof can exceed the sum of the members
A struct must be laid out so every member satisfies its alignment, and the whole struct is padded so that an array of structs keeps every element aligned. A struct containing a char followed by an int on a platform with four-byte ints is therefore eight bytes, not five: the char occupies byte 0 and three padding bytes fill bytes 1 through 3, so the int starts at byte 4. This is why reading a file or a network message directly into a struct with a memcpy from raw bytes can misinterpret the padding, and why fixed-size binary formats define field offsets explicitly rather than relying on the compiler's struct layout. The bit-manipulation session shows how to decode such a buffer field by field.
A a pointer that still holds an address after the object at that address has gone out of scope or been freed, so using it is undefined behaviour is the other advanced hazard, and it follows directly from lifetime. A function's local variables live only for the duration of that call, so returning the address of a local hands the caller a pointer to memory that no longer holds a valid object:
int *bad(void)
{
int local = 7;
return &local; /* dangling: local dies when bad returns */
}
Using the returned pointer is undefined behaviour. The symptom is often subtle: the value reads correctly for a while, because the stack bytes have not been overwritten yet, and then changes for no reason when another call reuses that space. The diagnosis is to watch for the address of a local leaving its function, and the fix is to return the value itself, or to point at an object with a longer lifetime, such as a static variable or, in a later session, heap memory from malloc.
The most dangerous dangling-pointer bug is the one that works. If the stale address is reused before the bytes are overwritten, the program appears fine in testing and fails later under a different call order. Treat any pointer to a local that outlives its function as a bug even when it seems to work.
Strict aliasing and common pointer mistakes
3 min readthe rule that an object may only be accessed through an lvalue of a compatible type, or through a character type, so access through an incompatible pointer type is undefined behaviour is the reason the compiler is allowed to assume two pointers of unrelated types never point at the same object. Given an int, you may access it through an int *, and you may inspect its bytes through a char *, signed char * or unsigned char *, but accessing it through, say, a float * is undefined behaviour. This lets the compiler reorder and cache loads and stores on the assumption that a write through one type cannot change a value read through another.
int i = 0x12345678;
float *f = (float *)&i; /* incompatible type */
float x = *f; /* undefined behaviour */
The trap is that this often works at -O0 and breaks only when optimisation is enabled, because it is at -O2 and above that gcc and clang apply the rule aggressively. The -fstrict-aliasing flag controls it; it is on by default at those optimisation levels, and -fno-strict-aliasing disables it, at the cost of the optimisations that depend on it. If you must reinterpret the bytes of an object as another type, the portable approach is to copy the bytes with memcpy, which is defined to move raw bytes regardless of type:
int i = 0x12345678;
float f;
memcpy(&f, &i, sizeof f); /* defined, copies the bytes */
A closely related rule covers reading the bytes of any object: iterate with an unsigned char *, as my_memcpy did, and you are within the letter of the standard. A character type is the one type through which any object's representation may be examined.
The rest of this session's hazards are worth collecting as symptom, cause and fix, because they are what professionals actually debug.
A pointer never assigned, dereferenced. Symptom: a crash at a random address, or a value read from nowhere. Cause: an uninitialised pointer holds an indeterminate address, and using it is undefined behaviour. Diagnosis: initialise every pointer when you declare it, to NULL or to the address you mean, and gdb will show a nonsense address before the crash. Fix: write int *p = NULL; until you have a real address, and test for NULL before dereferencing.
Off-by-one in pointer arithmetic. Symptom: the last or first element is corrupted, or a loop reads one element too many. Cause: advancing a pointer past the array, or dereferencing the one-past-the-end pointer. Diagnosis: print the pointer and the array bounds, or compare against a + n rather than a sentinel. Fix: loop with p < a + n and never dereference the end pointer.
Subtracting pointers from different arrays. Symptom: a meaningless or wildly wrong count. Cause: subtracting pointers into different objects is undefined behaviour, even though it often compiles. Diagnosis: confirm both pointers came from the same allocation or array. Fix: keep a separate count, or ensure both pointers trace to the same array.
Try it
1 min readOpen the lab for this session and build the swap-by-pointer example from this lesson, then extend it so one function returns both a quotient and a remainder through out-parameters. Walk a small int array with a pointer using p++ and print each address with %p and each value, then do the same walk with indexed access and confirm the two produce identical results. Finally compile a tiny program with gcc -g that stores the value 0x12345678 in an int, and use gdb x/4xb &i to dump the four bytes and confirm the little-endian layout, then try x/1dw and x/s on a short string. The practice pack walks through each step, from reading a pointer declaration right-to-left to the strict-aliasing check above.
Key takeaways
- A pointer is a variable that holds an address; & makes an address and * follows it.
- C passes every argument by value, including pointers, but a pointer lets a function reach and change a caller's object.
- p + n advances n * sizeof(*p) bytes, and subtracting two pointers into one array yields a ptrdiff_t element count.
- const T * protects the pointed-to object, T * const protects the pointer, and const T * const protects both.
- A pointer to a pointer is how a function sets a caller's pointer, and how argv and arrays of strings are represented.
- void* is the generic pointer, converted implicitly to and from any object pointer in C; uintptr_t stores an address as an integer.
- Every object has an address, memory is a byte array, and x86 and ARM are little-endian, so the least significant byte comes first.
- Accessing an object through an incompatible pointer type violates strict aliasing and is undefined behaviour.
Reflect
- Explain to a colleague, in two sentences: take the address of a variable with &, store it in a pointer, and read or write the object through *.
- Which objective are you least sure about? Re-read that section, then do its exercise in the practice pack.
- What surprised you when you ran the commands yourself?
On a real board
Repeat the key commands on your Raspberry Pi or lab board over SSH or the serial console. Note anything that behaves differently from your PC, such as missing tools, a BusyBox shell or a read-only filesystem.
References and further reading
- Official docscppreference.com: Pointer declaration
- Official docsGCC documentation: Options That Control Optimization (-fstrict-aliasing)
- Official docsDebugging with GDB: Examining Memory
- Man pagemalloc(3) - Linux man page (alignment guarantee)
- Official docsintptr_t, uintptr_t (C reference)
- SpecificationISO/IEC 9899:2011, the C11 standard, sections 6.3.2.3, 6.5.6 and 6.5.7
Official documentation first. Links checked when the lesson was published.