c / intermediate
Snippet
Dynamic Memory for Structs
Using malloc to allocate memory for structures on the heap is essential when the size or lifetime of the data isn't known at compile time.
snippet.c
1
2
3
4
5
6
7
typedef struct { int id; char *name; } User;User *u = (User *)malloc(sizeof(User));if (u != NULL) {u->id = 1;free(u);}
Breakdown
1
malloc(sizeof(User))
Allocates a block of memory of the exact size required for one User struct.
2
u->id = 1;
Uses the arrow operator to access a struct member via a pointer.
3
free(u);
Releases the allocated memory back to the system to prevent memory leaks.