Pointers
int x = 10;
int *p = &x;
printf("%d", *p); // 10
π₯ Dynamic allocation
#include <stdlib.h>
int *p = (int *) malloc(sizeof(int));
*p = 42;
allocates memory on heap
returns void* (generic pointer)
you cast it (optional in C, but people still do it)
β οΈ VERY IMPORTANT:
if (p == NULL) {
// allocation failed
}
π§Ό free
free(p);
free(p);
free(p); // π undefined behavior
𧨠malloc does NOT initialize memory
int *p = malloc(sizeof(int));
printf("%d", *p); // garbage value
int *p = (int *) malloc(5 * sizeof(int));
Allocates memory
Does NOT initialize it
Memory contains garbage values
π§ calloc
int *p = (int *) calloc(5, sizeof(int));
Allocates memory for 5 integers
Initializes everything to 0
π realloc (resizing memory)
p = realloc(p, 10 * sizeof(int));
resizes previously allocated memory
may move memory to a new location
So always:
int *temp = realloc(p, new_size);
if (temp != NULL) {
p = temp;
}
Because if realloc fails, your original pointer is still valid…
π¦ Arrays using pointers
int *arr = malloc(5 * sizeof(int));
arr[0] = 10;
arr[1] = 20;
// OR
*(arr + 1) = 20;
π§ Pointer arithmetic
int *p = arr;
p++; // moves to next int (not +1 byte)
C automatically adjusts by sizeof(type).
ποΈ Struct allocation
struct Person {
int age;
};
struct Person *p = malloc(sizeof(struct Person));
p->age = 25;
π§΅ Strings (char pointers)
char *str = malloc(6 * sizeof(char));
strcpy(str, "Hello");
Important: allocate space for \0
"Hello" = 5 chars + 1 null = 6
𧨠Dangling pointers
int *p = malloc(sizeof(int));
free(p);
printf("%d", *p); // π Pointer still existsβ¦ memory doesnβt.
Fix:
free(p);
p = NULL;
Now at least it fails safely.
β‘ Stack vs Heap
Stack
int x = 10;
automatic
fast
destroyed when function ends
int *p = malloc(sizeof(int));
manual
slower
YOU must free it
π§ͺ Common mistakes
// β Forgetting `sizeof`
int *p = malloc(5); // wrong
// β
Correct
int *p = malloc(5 * sizeof(int));
// β Using uninitialized pointer
int *p;
*p = 10; // π
// β Memory leak
p = malloc(...);
p = malloc(...); // lost reference to old memory
Last modified: 25 March 2026