Course contentsShow
← Computer Science
Lesson 2086 of 2,87247. Memory Management in LanguagesFree lesson

Memory Allocation Patterns

Common patterns for requesting memory: single objects, arrays, and structures with appropriate size calculations.

Memory Allocation Patterns

What you'll learn: How to correctly request memory for common data structures using appropriate size calculations.

When you call malloc() or similar allocation functions, you need to specify how much memory to allocate. Getting this right is critical—request too little and you'll corrupt memory; request too much and you waste resources. Different data needs follow distinct patterns.

Single Object Allocation

The simplest pattern allocates space for one object. You use the sizeof operator to determine the exact bytes needed:

int *ptr = (int *)malloc(sizeof(int));

This requests enough memory for exactly one integer, regardless of platform.

Array Allocation

Arrays require multiplying the size of one element by the number of elements you need:

int *arr = (int *)malloc(10 * sizeof(int));

This allocates space for 10 integers in a contiguous block. Think of it like reserving 10 parking spots in a row—you need to know both how many spots you want and how wide each spot needs to be.

Structure Allocation

For complex structures, use sizeof with the structure type. The compiler handles alignment and padding automatically:

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

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

You can also allocate arrays of structures by combining patterns:

struct Person *people = (struct Person *)malloc(5 * sizeof(struct Person));

This creates space for 5 complete Person records.

Why Size Calculations Matter

Always use sizeof rather than hardcoded numbers. It ensures portability across systems where types might have different sizes (e.g., int might be 4 bytes on one platform, 8 on another).

Key Takeaway: Memory allocation patterns follow simple formulas—single objects use sizeof(type), arrays use count * sizeof(type), and structures use sizeof(struct_name)—ensuring you request exactly the right amount of memory every time.