Course contentsShow
← C
Lesson 620 of 1,2199. Structures and UnionsFree lesson

Allocating structs on the heap with malloc

Allocating structs on the heap with malloc

What you'll learn: How to use malloc to create structures that live in the heap memory, allowing them to persist beyond the scope of a single function.

Why use the heap for structs?

Up until now, you have likely been creating structures as local variables. When you write struct Player p1; inside a function, that memory is carved out of the "stack." The moment that function finishes, p1 is destroyed.

However, in real-world applications—like a game engine or a database—you often need data to stick around. By using malloc, you request memory from the "heap." This memory stays reserved for you until you explicitly call free. This is essential for building complex data structures like linked lists or trees.

The syntax of heap allocation

To allocate a struct on the heap, you need a pointer to hold the address returned by malloc. You must also use sizeof to ensure you request exactly enough bytes to fit the entire structure.

Because malloc returns a generic pointer (void*), you should cast it to your specific struct pointer type. Once allocated, you use the "arrow operator" (->) to access the members, because you are dealing with a pointer rather than the struct itself.

A concrete example

Imagine we are creating a character for a role-playing game. We want the character to persist even after the "creation" function ends.

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

struct Character {
    int health;
    int level;
};

int main() {
    // 1. Allocate memory for one Character struct on the heap
    struct Character *hero = (struct Character *)malloc(sizeof(struct Character));

    // Check if allocation was successful
    if (hero == NULL) {
        return 1; 
    }

    // 2. Access members using the arrow operator
    hero->health = 100;
    hero->level = 1;

    printf("Hero Level: %d, Health: %d\n", hero->level, hero->health);

    // 3. Always free the memory when finished
    free(hero);

    return 0;
}

Thinking about size

When you call malloc(sizeof(struct Character)), the computer looks at your struct definition, adds up the bytes for the int health and int level, and finds a contiguous block of memory that fits. By using a pointer, you are essentially holding a "remote control" to that block of memory. Just remember the golden rule of the heap: for every malloc, there must be a free. If you lose the pointer before calling free, you have a memory leak!

Key takeaway

Use malloc with sizeof(struct YourStruct) to create persistent data on the heap, and always access its members using the arrow (->) operator.