← Back to C Course | Chapter 9: Memory Management | Lesson 7 of 8

C Dynamic Struct Allocation

A struct can be allocated on the heap with malloc(sizeof(struct Name)), accessed through the -> operator, and freed like any other block, with nested pointer members requiring their own separate allocation and free.

Dynamically Allocating a Struct

A struct can be dynamically allocated on the heap using malloc(sizeof(struct StructName)), which reserves exactly enough memory to hold one instance of that struct, accessed through a pointer.

Example: Dynamically Allocating a Struct

c
#include <stdio.h>
#include <stdlib.h>
struct Point { int x; };
int main() {
	struct Point *p = malloc(sizeof(struct Point));
	p->x = 5;
	printf("%d", p->x);
	free(p);
	return 0;
}

Accessing Members with ->

The -> operator accesses a member of a struct through a pointer in a single step, combining what would otherwise be a dereference followed by the dot operator, written as (*p).member.

Example: Accessing Members with ->

c
#include <stdio.h>
#include <stdlib.h>
struct Point { int x; };
int main() {
	struct Point *p = malloc(sizeof(struct Point));
	p->x = 10;
	printf("%d", p->x);
	free(p);
	return 0;
}

Allocating an Array of Structs

An entire array of structs can be dynamically allocated at once by multiplying sizeof(struct StructName) by the desired element count, and each struct in the array is then accessed with regular indexing.

Example: Allocating an Array of Structs

c
#include <stdio.h>
#include <stdlib.h>
struct Point { int x; };
int main() {
	struct Point *points = malloc(3 * sizeof(struct Point));
	points[1].x = 7;
	printf("%d", points[1].x);
	free(points);
	return 0;
}

Freeing a Dynamically Allocated Struct

A dynamically allocated struct, whether a single instance or an array of them, is released with a single call to free, exactly as with any other block of memory obtained from malloc.

Example: Freeing a Dynamically Allocated Struct

c
#include <stdio.h>
#include <stdlib.h>
struct Point { int x; };
int main() {
	struct Point *p = malloc(sizeof(struct Point));
	p->x = 1;
	free(p);
	return 0;
}

Structs with Dynamically Allocated Members

When a struct contains a pointer member that itself points to separately allocated memory, such as a dynamically sized name string, that inner allocation must be freed first, followed by the struct itself, to avoid leaking the inner memory.

Example: Structs with Dynamically Allocated Members

c
#include <stdio.h>
#include <stdlib.h>
struct Person { char *name; };
int main() {
	struct Person *p = malloc(sizeof(struct Person));
	p->name = malloc(10);
	free(p->name);
	free(p);
	printf("Freed inner then outer");
	return 0;
}
🔒

Chapter Quiz — Complete all 8 topics to unlock

0/8 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.