CodeBlanks Logo Icon CodeBlanks

Dynamic struct

  • C course
  • Intermediate
  • Lesson 31/116
  • 5 min

Learn to allocate memory for a struct with malloc.

Dynamic struct

To keep a struct on the heap for its lifetime, you use malloc. The call struct Person *p = malloc(sizeof(struct Person)); allocates enough bytes from the heap and returns a pointer.

sizeof(struct Person) gives the byte count the struct needs; you don't have to compute it by hand. The return type is void*; in C it's implicitly converted to struct Person*. On failure it returns NULL; that's why you must check before use. When done, call free(p) to release the memory.

free and NULL check

malloc isn't always successful; if memory is full it returns NULL. Accessing a NULL pointer is undefined behavior; that's why checking is required.

Example pattern: struct Person *p = malloc(sizeof(struct Person)); if (p == NULL) return 1; p->age = 25; ... free(p);. free(p) releases memory but doesn't set p to NULL; so writing p = NULL after free is a good habit. Every malloc needs a free; a missing free creates a memory leak.

Practice Create and print a dynamic struct

Define struct Person with char name[32]; and int age;. In main, allocate with struct Person *p = malloc(sizeof(struct Person));. Check with if (p == NULL) return 1;. Assign p->age = 25;, print with printf("%d\n", p->age);, then call free(p);.

Starter code

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

// Define struct Person (name[32] and age)
// Allocate memory for p with malloc
// Set age to 25 via p, print, then call free

int main(void) {
    return 0;
}

Sample solution

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

struct Person {
    char name[32];
    int age;
};

int main(void) {
    struct Person *p = malloc(sizeof(struct Person));
    if (p == NULL) return 1;
    p->age = 25;
    printf("%d\n", p->age);
    free(p);
    return 0;
}

Expected output

25

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 Match the malloc expressions

Term Meaning
malloc(sizeof(struct Person)) Allocation
p->age = 25 Field assignment
free(p) Release
p == NULL Null check

2 What does malloc return on failure?

  • NULL Correct answer
  • 0
  • -1
  • Empty struct

Explanation: malloc returns NULL on failure; that's why checking is required.

3 Complete the malloc call

Question
struct Person *p = ____(sizeof(struct Person));
Answer
struct Person *p = malloc(sizeof(struct Person));

Explanation: malloc allocates heap memory for the struct.

All lessons in Intermediate