C malloc()
In this page:
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
#include <stdio.h>
#include <stdlib.h>
int main() {
int *ptr = malloc(sizeof(int));
*ptr = 5;
printf("%d", *ptr);
free(ptr);
return 0;
}
Login to try C/C++/Java/PHP code in the editor
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
#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;
}
Login to try C/C++/Java/PHP code in the editor
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
#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;
}
Login to try C/C++/Java/PHP code in the editor
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()
#include <stdio.h>
#include <stdlib.h>
int main() {
int *ptr = malloc(sizeof(int));
*ptr = 10;
printf("%d", *ptr);
free(ptr);
return 0;
}
Login to try C/C++/Java/PHP code in the editor
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()
#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;
}
Login to try C/C++/Java/PHP code in the editor
Chapter Quiz — Complete all 8 topics to unlock
0/8 topics done
Complete these topics first: