lecture 07
讲堆、栈、内存等,依旧讲得很好Lecture07.pdflive_session.cpig_latin.cpig_latin_soln.c
The Stack




• The stack behaves like a…well…stack! A new function call pushes on a new frame. A completed function call pops off the most recent frame.
• Interesting fact: C does not clear out memory when a function’s frame is removed. Instead, it just marks that memory as usable for the next function call. This is more efficient!
• A stack overflow is when you use up all stack memory. E.g. a recursive call with too many function calls.
• What are the limitations of the stack?
The Heap and Dynamic Memory


• This function returns a pointer to the starting address of the new memory. It doesn’t know or care whether it will be used as an array, a single block of memory, etc.
• void *means a pointer to generic memory. You can set another pointer equal to it without any casting.
• The memory is not cleared out before being allocated to you!
• If malloc returns NULL, then there wasn’t enough memory for this request.


calloc分配清理过的内存,但是更expensive,malloc分配没有清理过的内存。


Memory Leaks
• A memory leak is when you allocate memory on the heap, but do not free it.
• Your program should be responsible for cleaning up any memory it allocates but no longer needs.
• If you never free any memory and allocate an extremely large amount, you may run out of memory in the heap!
However, memory leaks rarely (if ever) cause crashes.
• We recommend not to worry about freeing memory until your program is written. Then, go back and free memory as appropriate.
• Valgrind is a very helpful tool for finding memory leaks!
realloc


• realloc only accepts pointers that were previously returned by malloc/etc.
• Make sure to not pass pointers to the middle of heap-allocated memory.
• Make sure to not pass pointers to stack memory.
You only need to free the new memory coming out of realloc—the previous (smaller) one was already reclaimed by realloc.
A summary
Engineering principles: stack vs heap

Heap allocation is a necessity when:
• you have a very large allocation that could blow out the stack
• you need to control the memory lifetime, or memory must persist outside of a function call
• you need to resize memory after its initial allocation
strdup means string duplicate
In the news: Heap buffer overflow
strdupcat





