Lesson 104 +10 XP

Memory with Structs

Memory with Structs

Structs and dynamic memory team up to build flexible data like linked lists.

Allocating a struct

typedef struct {
    char name[50];
    int age;
} Person;

Person *p = malloc(sizeof(Person));

Access fields through the pointer

strcpy(p->name, "Ada");
p->age = 36;

The stack vs heap split

  • Stack - automatic variables (small, fast).
  • Heap - dynamic memory (bigger, manual).

malloc gets memory from the heap.

Free the whole struct

free(p);

One free for the one malloc.

TL;DR

  • malloc can allocate whole structs.
  • Use the arrow to access fields.
  • Structs live on the heap with malloc.
  • Free each malloc exactly once.