A structured lesson workspace with readable content, hands-on examples, and a clean path to completion.
A dangling pointer points to memory that has been freed or is otherwise no longer valid. The pointer still holds an address. The address still looks plausible. But the data at that address belongs to someone else now, or to no one. Dereferencing a dangling pointer is undefined behavior. It might read stale data. It might read another allocation's data. It might crash. It might appear to work correctly for months and then corrupt a database during a Friday deployment. This is the hardest class of C bug to diagnose because the symptom appears far from the cause.
#include <stdio.h>#include <stdlib.h>#include <string.h>char *get_greeting(void) {char buf[64];strcpy(buf, "Hello from the stack!");return buf;}int main(void) {char *msg = get_greeting();printf("Message: %s\n", msg);return 0;}
buf is a stack-local array. When get_greeting returns, its stack frame is popped. buf no longer exists. The returned pointer points to reclaimed stack space. The printf reads whatever happens to be there. In this run, it printed garbage. In another run, it might print the correct string if nothing overwrote the stack yet. That inconsistency is what makes dangling pointers so dangerous. They sometimes work.
#include <stdio.h>#include <stdlib.h>#include <string.h>int main(void) {char *token = malloc(32);strcpy(token, "session_abc123");printf("Token: %s\n", token);free(token);char *other = malloc(32);strcpy(other, "overwritten!!!");printf("After free: %s\n", token);free(other);return 0;}
token was freed. The allocator reused the same block for other. The printf through token reads other's data. Without ASan, this prints "overwritten!!!" and you might not even notice the bug because the program does not crash. With ASan, you get an immediate report with the exact line. In a security context, this is how attackers read session tokens, encryption keys, and credentials from freed heap blocks.
Set pointers to NULL immediately after free. Use ASan in every test run. Minimize the lifetime of pointers: allocate, use, free, nullify in the tightest scope possible. Avoid returning pointers to local variables. If a function must return dynamically allocated memory, document that the caller owns the free. These are not optional best practices. They are the minimum discipline required to write C that does not corrupt memory.
Dangling pointers are the root cause of use-after-free vulnerabilities, which consistently rank among the most exploited memory safety bugs. The defense is procedural: nullify after free, minimize pointer lifetimes, and run ASan relentlessly. Next: the malloc typecast debate, a style argument that has raged since the 1980s.
Finish the lesson once you have worked through the material. This awards ★ 40 XP.