Skip to content
Guest
Learn C · Course Syllabus Show lessons
Memory & Data · 9 min read · Intermediate

Structs, typedef & Heap Memory (malloc/free)

Group related fields into custom structs, access fields via ->, and allocate dynamic heap memory safely.

What you'll learn

  • Define clean composite types with typedef struct
  • Use dot (.) on struct values and arrow (->) on struct pointers
  • Allocate heap memory with malloc, check for NULL, and release it with free

A struct groups related fields of different types into one contiguous record. When you need data whose size is determined at runtime or must outlive a function call, allocate it on the heap with malloc() and always pair it with free().

Dot (.) vs. Arrow (->)

  • Use user.age when you have a User value.
  • Use ptr->age (shorthand for (*ptr).age) when you have a User * pointer.

Fill-in-the-Blank Exercise

Heap Allocation & Cleanup

Allocate memory for 4 integers on the heap and free it before returning.

int *nums = (4 * sizeof(int));
if (nums != NULL) {
  nums[0] = 7;
  (nums);
}

Interactive Code Lab

Cstructs_heap.c
Expected OutputClick “Run Live” to compile with GCC 13 (C11)
Maya scored 95

Check Your Understanding

Score: 0 / 1

1. Given Student *ptr, how do you access the score field cleanly?

Study Workspace

Finished this lesson?

Your progress is saved locally in your browser, no account needed.

Search courses, lessons, and references

Type to search across all courses, lessons, and quick references.

Press Esc to close Powered by Pagefind