C Pointer: My take

Introduction
Pointers in C are like relationships- powerful, complicated, and if you mess up, everything crashes.
Ever wondered why your program randomly throws a segmentation fault? That’s because you tried to access memory like a hacker in a Hollywood movie. But don’t worry! By the end of this post, you’ll (hopefully) be handling pointers with fewer breakups.
What is a Pointer?
A pointer is just a variable that stores the address of another variable.
Think of it like:
A regular variable stores data.
A pointer stores where that data is in memory(the address of that data).
Example:
# include <stdio.h>
int main() {
int x = 10;
int* ptr_1 = &x; // Pointer storing address of a
print("Value of x: %d \n", x);
print("Address of x: %p \n", &x);
print("Value of ptr_1: %p \n", ptr_1); // Value inside the ptr(which is address of x)
print("Value at the address stored in ptr_1: %d \n", *ptr_1); //Dereferencing the ptr
return 0;
}
Output:
Value of x: 10
Address of x: 0×7ffeefbff5dc
Value of ptr_1: 0×7ffeefbff5dc
Value at the address stored in ptr_1: 10
Here, ptr_1 stores the memory address of x, and *ptr_1 (dereferencing) gets the actual value from that address.
Why use Pointers?
Because they make things faster, flexible, and slightly terrifying.
Dynamic memory allocation.
Efficient data structures(like linked lists, and trees).
Passing large data structures to functions without copying them.
Common Pointer Mistakes(And How to Avoid Them)
Forgetting to Allocate Memory (NULL Pointer)
int* aptr;
*aptr = 42; // BOOM! Segmentation fault(aptr doesn't point to any variable,
// so can't dereference it)
FIX: Always initialize your pointer before using them.
int x = 42;
int* aptr= &x;
Or use malloc when dealing with dynamic memory (allocating memory on heap).
Dereferencing a Freed Pointer (Use-After-Free)
int *ptr = (int*)malloc(sizeof(int);
free(ptr);
*ptr = 10; // still trying to use the freed pointer. Segmentation fault
FIX: After freeing, Set it to NULL.
free(ptr);
ptr = NULL;
Pointer Arithmetic Gone Wrong
Pointers allow arithmetic operations, but if you move the pointer too far, you’re in “undefined behaviour” land.
int arr[3] = {1, 3, 2};
int *ptr = arr;
ptr +=5; // YOu just crossed into unallocated memory(arr had only 3 bytes), RIP
FIX: Stay within the array(data struct) memory bounds!
Conclusion
Pointers are powerful but dangerous. Treat them like sharp knives-use them carefully, and they’ll make you a great coder.
Next time your code crashes, remember:
if you see a Segmentation Fault (core dumped), Blame the pointer
If it works perfectly, pretend it was intentional.
Want to dive deeper? Check out my next blog on Memory management!
What Did You Think?
Have you ever faced a nightmare debugging a pointer issue? Share your horror stories in the comments!
Subscribe to my newsletter
Read articles from Abhay Singh directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by
