14. Memory API Flashcards
How allocation and de-allocations are managed on stack and heap?
Stack - automatically by compiler. Heap - manually by programmer.
What call can be used to request memory in heap? What does it return?
malloc(size_t size). It returns pointer to void so programmer can cast it to needed type on its own.
Is sizeof() a run-time or compile-time thing?
It’s an operator and it’s a compile-time thing
What call can be used to free memory in heap?
free(pointer).
What are most common issues with allocating memory?
Not allocation enough memory, forgetting to initialize allocated memory (uninitialized read), forgetting to free memory, freeing memory before you are done with it (dangling pointer), freeing memory repeatedly, invalid free
Since malloc() and free() are library functions and not system calls, what system calls are used to allocate memory?
brk() - used to change the location of program’s break: the location of the end of the heap. It takes address of new break as arugment.
Another call is sbrk() which serves same purposes, but takes an increment value
mmap() - creates anonymous memory region within program, a region which is not associated with any file but rather with swap space
calloc() - allocated memory and also zeroes it out
realloc() - makes a new larger region of memory and copies old region into it