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

C malloc()

Dynamic Memory Allocation

This is different from stack memory, which is automatically sized and reclaimed when a function returns -- heap memory persists until you explicitly free it, and its size can be decided while the program is actually running, based on real input.

Example: Dynamic Memory Allocation

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

The malloc() Function

Because malloc() returns a generic void pointer, you typically cast it to the type you need, e.g. int *arr = (int*)malloc(10 * sizeof(int)) -- note that the memory is uninitialized, containing whatever garbage bytes were previously there.

Example: The malloc() Function

c
#include <stdio.h>
#include <stdlib.h>
int main() {
	int *arr = (int*)malloc(10 * sizeof(int));
	arr[0] = 1;
	printf("%d", arr[0]);
	free(arr);
	return 0;
}

Checking Allocation Success

This check is not optional in production code -- dereferencing the NULL that a failed malloc() returns crashes your program immediately, and on systems with limited memory, allocation failures are a real possibility, not just a theoretical edge case.

Example: Checking Allocation Success

c
#include <stdio.h>
#include <stdlib.h>
int main() {
	int *ptr = malloc(sizeof(int));
	if (ptr == NULL) {
		printf("Allocation failed");
		return 1;
	}
	*ptr = 5;
	printf("%d", *ptr);
	free(ptr);
	return 0;
}

Freeing Memory with free()

Skipping this step causes a memory leak: the allocated block becomes unreachable once you lose the pointer to it (e.g. the pointer variable goes out of scope), but the operating system still considers that memory 'in use' until the program exits.

Example: Freeing Memory with free()

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

Dynamic Arrays with malloc()

The multiplication (count * sizeof(type)) ensures you request exactly the right number of bytes regardless of the target platform's specific type sizes, which can differ between systems -- always use sizeof rather than hardcoding a byte count.

Example: Dynamic Arrays with malloc()

c
#include <stdio.h>
#include <stdlib.h>
int main() {
	int count = 5;
	int *arr = malloc(count * sizeof(int));
	for (int i = 0; i < count; i++) {
		arr[i] = i;
	}
	printf("%d", arr[4]);
	free(arr);
	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.