Prev: the-abstraction-address-spaces Next: mechanism-address-translation
In C, there are two types of memory: stack memory (automatic memory) where allocations and deallocations are managed by the compiler, and heap memory, where all allocations and deallocations are handled by you.
#include <stdlib.h>
int x = 5; // automatic memory
int* y = malloc(sizeof(int)); // heap memory
*y = 5;
Malloc requires an argument, the size of the block of memory you
want. This returns a void *
pointer, which is returned for
you to cast.
Once you malloc memory, you must free it, otherwise this will cause a memory leak.
char *src = "hello";
char *dst; // oops! unallocated
(dst, src); // segfault and die strcpy
char *src = "hello";
char *dst = (char *) malloc(strlen(src)); // too small!
(dst, src); // work properly strcpy