malloc
- C course
- Beginner
- Lesson 102/116
- 5 min
Learn to allocate memory on the heap with malloc.
malloc: allocating heap memory
malloc allocates memory on the heap and returns its starting address. It comes with the <stdlib.h> header. Its signature is void *malloc(size_t size).
int *p = malloc(sizeof(int));
*p = 100;
// p points to 4 bytes on the heapsizeof(int) gives the byte size of an int; this is required for portable code. malloc does not zero the memory; old data may remain. The return value is void * so it can be assigned to any pointer directly.
Portable size with sizeof
Always pass sizeof to malloc. It asks the compiler for the byte size of a type; the same code runs on different systems.
int *p = malloc(sizeof(int));
double *d = malloc(sizeof(double));
int *arr = malloc(5 * sizeof(int));The last example allocates space for an array of 5 ints. The expression 5 * sizeof(int) gives the total byte count for 5 elements. This approach makes the code work on both 32-bit and 64-bit systems.
Practice Allocate an int with malloc and print
Allocate heap memory for one int with malloc; assign the pointer to int *p. Set *p = 100 and print it with printf. Include the <stdlib.h> header.
Starter code
#include <stdio.h>
int main(void) {
/* Allocate an int with malloc; *p = 100; print with printf */
return 0;
}Sample solution
#include <stdlib.h>
int *p = malloc(sizeof(int));
*p = 100;
printf("%d\n", *p);Expected output
100
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Fill in the blank: malloc call
int *p = ____(sizeof(int));
int *p = malloc(sizeof(int));
Explanation: malloc allocates heap memory.
2 Match call to purpose
| Term | Meaning |
|---|---|
malloc(sizeof(int)) |
Space for one int |
malloc(5 * sizeof(int)) |
Space for 5 ints |
sizeof(int) |
Bytes of an int |
void * |
Return type |
3 What does malloc return?
- The size of the memory
- An int value
- The starting address of the allocated memory Correct answer
- A pointer count
Explanation: malloc returns the starting address of the allocated memory.