Pointers are powerful but tricky in C. Here are the most common mistakes beginners and even experienced C programmers make, along with explanations and how to avoid them.
❌ Uninitialized Pointer
int *ptr; // uninitialized — points to random memory
*ptr = 42; // undefined behavior!
✅ Fix: Always initialize pointers before use.
int x = 42;
int *ptr = &x;
❌ Dereferencing a NULL Pointer
int *ptr = NULL;
printf("%d\n", *ptr); // Crash: dereferencing NULL
✅ Fix: Check for NULL before dereferencing.
if (ptr != NULL) {
printf("%d\n", *ptr);
}
❌ Double Free
free(ptr);
free(ptr); // undefined behavior
✅ Fix: Set pointer to NULL after freeing.
free(ptr);
ptr = NULL;
❌ Pointer Arithmetic on Invalid Memory
int *ptr = malloc(5 * sizeof(int));
int *end = ptr + 10; // out-of-bounds
✅ Fix: Never go beyond the allocated range.
❌ Returning Pointer to Local Variable
int *getPtr() {
int x = 5;
return &x; // x is destroyed after return!
}
✅ Fix: Use malloc() to return persistent memory, or use static/global vars.
✅ Pro Tips
- Use valgrind or asan to detect memory issues.
- Always initialize pointers to NULL if you’re not assigning them immediately
- Prefer sizeof(*ptr) over sizeof(type) when allocating memory.
- Document ownership: who allocates and who frees the pointer.
Top comments (0)