Table of Contents

Memory Management

In C, you can manually manage memory to have greater control.

Stack and Heap

Local variables are automatically allocated on the stack when they come into scope. They are deallocated (memory is freed) when they exit their scope. The stack grows from top to bottom.

Manually allocated memory is put on the heap. The heap grows from bottom to top.

Functions

<stdlib.h>

malloc

void* malloc(size_t size)

free

free(void* p)

memset

void* memset(void s[n], int c, size_t n)

calloc

void* calloc(size_t n, size_t size)

realloc

void* realloc(void* p, size_t size)

Example

char *p = malloc(sizeof(char * 64));
// char *p = malloc(sizeof(*p * 12)); <<-- *p is a char, same effect as above
 
// always error check malloc
if (p == NULL) {
	fprintf(stderr, "Call to malloc failed! Aborting...\n");
	exit(1);
}
 
// use p
strcpy(p, "malloced string");
puts(p);
 
// free memory, else memory leak
free(p);