程序代写代做代考 MINI VALGRIND

MINI VALGRIND

• •

TO LEARN
Learn how Valgrind works
Learn memory layout and how malloc/free works
How does free know how many bytes it has to free?

• •
• •



MALLOC/FREE & MEMORY LAYOUT
How does free know how many bytes to free? How does those ‘free block’ be reused?
You need some meta data to tell you the size of a memory block
Put them into a list when you free memory blocks When malloc
Find a block in the list that is big enough Grow heap otherwise


Learn how to create meta data and combine them with memory asked by users
META_DATA
MINI VALGRIND
MEMORY

Learn how to use linked-list to link memory blocks
META_DATA META_DATA
MEMORY
MEMORY





MINI VALGRIND
mini_malloc(size_t size, const char * file, size_t line) use system malloc to get memory
create meta data
put the memory in a list update total_usage
• • •
mini_free(void * ptr) remove from list
use system free to free memory update total_free
• •

ptr
MEMORY LAYOUT
mini_malloc()
malloc() get
ptr2
return
ptr is for you ptr2 is for user
MEMORY
NEXT
SIZE
META_DATA
MEMORY
META_DATA
MEMORY

ptr
ptr2
MEMORY LAYOUT
META_DATA
MEMORY






How to calculate ptr/ptr2 from ptr2/ptr?
Malloc
Get ptr return ptr2
Free
Get ptr2 return ptr
MEMORY LAYOUT DONEC QUIS NUNC



• •
• • •
HINT
Global variables in mini_valgrind.c meta_data * head : head for linked-list
total_usage: keep track of bytes used
total_free: keep track of bytes freed
Think about how to create a linked-list and insert/remove Insert has to be constant time
Have to catch the bad call of free(like double free).

DEMO

DEMO
DOUBLE FREE

DEMO
memory leak: ptr4