C Notes Help

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