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

C malloc()

malloc asks the computer for a chunk of memory while the program runs, like borrowing a table at a restaurant. You must check you got it and give it back when finished.
Syntax
c
#include <stdlib.h>

data_type *pointer_name = (data_type *) malloc(count * sizeof(data_type));

if (pointer_name == NULL) {
  // allocation failed
}

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 standard input/output (printf, scanf)
#include <stdio.h>
// Include general utilities (malloc, free, exit)
#include <stdlib.h>
// Program execution starts in main()
int main() {
	// Allocate memory on the heap
	int *ptr = malloc(sizeof(int));
	*ptr = 5;
	// Print formatted text to the screen
	printf("%d", *ptr);
	// Release the heap memory so it can be reused
	free(ptr);
	// Return 0 to signal that the program finished successfully
	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 standard input/output (printf, scanf)
#include <stdio.h>
// Include general utilities (malloc, free, exit)
#include <stdlib.h>
// Program execution starts in main()
int main() {
	// Allocate memory on the heap
	int *arr = (int*)malloc(10 * sizeof(int));
	arr[0] = 1;
	// Print formatted text to the screen
	printf("%d", arr[0]);
	// Release the heap memory so it can be reused
	free(arr);
	// Return 0 to signal that the program finished successfully
	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 standard input/output (printf, scanf)
#include <stdio.h>
// Include general utilities (malloc, free, exit)
#include <stdlib.h>
// Program execution starts in main()
int main() {
	// Allocate memory on the heap
	int *ptr = malloc(sizeof(int));
	// Check whether ptr == NULL
	if (ptr == NULL) {
		// Print formatted text to the screen
		printf("Allocation failed");
		// Send 1 back to the caller
		return 1;
	}
	*ptr = 5;
	// Print formatted text to the screen
	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 standard input/output (printf, scanf)
#include <stdio.h>
// Include general utilities (malloc, free, exit)
#include <stdlib.h>
// Program execution starts in main()
int main() {
	// Allocate memory on the heap
	int *ptr = malloc(sizeof(int));
	*ptr = 10;
	// Print formatted text to the screen
	printf("%d", *ptr);
	// Release the heap memory so it can be reused
	free(ptr);
	// Return 0 to signal that the program finished successfully
	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 standard input/output (printf, scanf)
#include <stdio.h>
// Include general utilities (malloc, free, exit)
#include <stdlib.h>
// Program execution starts in main()
int main() {
	// Declare count and set it to 5
	int count = 5;
	// Allocate memory on the heap
	int *arr = malloc(count * sizeof(int));
	// Loop: repeat while the condition holds
	for (int i = 0; i < count; i++) {
		arr[i] = i;
	}
	// Print formatted text to the screen
	printf("%d", arr[4]);
	// Release the heap memory so it can be reused
	free(arr);
	return 0;
}
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the view already swaps in the hi_ translation fields (or blanks these out if untranslated), so this renders correctly for both languages without a lang_code check here. #}
Common Mistakes
  1. Not checking whether malloc returned NULL before using the memory.
  2. Forgetting to call free, so the memory leaks until the program ends.
  3. Allocating n bytes when n elements are needed, instead of n * sizeof(type).
🔒

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.