index

Interlude: Memory API

Types of Memory

  • stack/automatic memory
  • heap memory

stack memory is deallocated when you move out of the function call, to keep it permanent allocate on the heap

malloc()

argument is size_t use sizeof(), which is a compile-time operator. (compile-time operator, run-time function)

NOTE

C does not need you to cast the return of malloc back to the correct type, C++ does though

free()

int *x = malloc(10 * sizeof(int));
free(x);

Common Errors

1. Forgetting to Allocate Memory

char* src = "hello";
char* dst; // try char* dst = strdup(src);
strcpy(dst, src); // segfault and die (works on some machines tho)

2. Not Allocating Enough Memory

buffer overflow :)

[1] https://www.cs.cornell.edu/courses/cs5431/2011sp/readings/buffer_overflows_attacks_defenses.pdf

3. Forgetting to Initialize Allocated Memory

uninitialized read, some garbage value

4. Forgetting to Free Memory

memory leak: this remains a problem even in modern languages because if you have a reference to useless memory somewhere it’s not going to free on its own

5. Freeing Memory before you are Done with it

dangling pointer

6. Freeing Memory Repeatedly

double free: undefined

7. Calling free() Incorrectly

invalid free

TIP

[2] https://people.cs.umass.edu/~emery/pubs/pldi028-novark.pdf tips of memory management

Underlying OS Support

malloc and free are not syscalls, they are library calls. They make use of the brk and sbrk syscalls which change the location of a programs break i.e. the location of the end of the heap, so it can change the size of the heap

There is also the mmap syscall which can create an anonymouse memory region associated with swap space within your program

Other Calls

calloc() realloc()

[3] https://github.com/Lincheng1993/apue/blob/master/Advanced%20Programming%20in%20the%20UNIX%20Environment%203rd%20Edition.pdf advanced programming in the unix environment