28 November 2026

C Pointers, Structs, and Dynamic Memory (malloc/free) for Beginners

  Asp.Net CS By Example       28 November 2026

Understanding pointers, structs, and dynamic memory (malloc and free) is the milestone that turns C from a mysterious language into a crystal-clear mental model of how computers store data. In this beginner lesson, you will allocate a dynamic array of student structs at runtime, access fields through pointers, and release memory safely.

Heap memory lifecycle in C

malloc(count * sizeof(Student)) → Check ptr != NULL → Read/Write via ptr[i] or ptr->field → free(ptr); ptr = NULL;

Pointers and the -> Operator

  • A pointer stores the memory address of a value rather than copying the whole struct.
  • When you have a struct variable s, use a dot (s.score). When you have a pointer p to a struct, use the arrow operator (p->score).
  • Every successful malloc(...) or calloc(...) call must be paired with exactly one free(...) call when you finish using the block.

Complete Dynamic Student Array Example

Save this program as students.c and compile with gcc -Wall -Wextra students.c -o students:

#include <stdio.h>
#include <stdlib.h>

typedef struct {
    int id;
    char name[32];
    int score;
} Student;

void print_student(const Student *s) {
    printf("ID: %d | Name: %s | Score: %d\n", s->id, s->name, s->score);
}

int main(void) {
    size_t count = 2;
    Student *roster = malloc(count * sizeof(Student));
    if (roster == NULL) {
        fprintf(stderr, "Memory allocation failed.\n");
        return 1;
    }

    roster[0] = (Student){101, "Aarav", 92};
    roster[1] = (Student){102, "Maya", 89};

    for (size_t i = 0; i < count; i++) {
        print_student(&roster[i]);
    }

    free(roster);
    roster = NULL;
    return 0;
}

Three Safety Rules for Beginners

  1. Always check for NULL: Never dereference a pointer returned by malloc before checking if (roster == NULL).
  2. Pass structs by const pointer: print_student(const Student *s) avoids copying the struct and promises the function will not modify it.
  3. Reset freed pointers to NULL: Setting roster = NULL; after free(roster) prevents accidental use-after-free bugs.

Practice

  1. Add a function double average_score(const Student *roster, size_t count) that loops through the dynamic array and returns the class average.
  2. Use realloc to grow roster from 2 students to 3 students and add a third student record.
  3. Compile with AddressSanitizer (gcc -fsanitize=address -g students.c) and intentionally test omitting free(roster) to watch the leak detector report it.

Continue learning: C Lessons and Practice.

References: cppreference.com C Standard Reference.

logoblog

Thanks for reading C Pointers, Structs, and Dynamic Memory (malloc/free) for Beginners

Previous
« Prev Post

No comments:

Post a Comment

Please do not enter any spam link in the comment box.