Malloc package P731 ·# include< stdlib. h> void * malloc(size t size if successful returns a pointer to a memory block of at least size bytes, aligned to 8-byte boundary if size==0. returnS NULL if unsuccessful returnS null void free( void*p returns the block pointed at by p to pool of available memory p must come from a previous call to malloc, calloc or realloc
6 Malloc package P731 • #include <stdlib.h> • void *malloc(size_t size) – if successful: • returns a pointer to a memory block of at least size bytes, aligned to 8-byte boundary. • if size==0, returns NULL – if unsuccessful: returns NULL • void free(void *p) – returns the block pointed at by p to pool of available memory – p must come from a previous call to malloc,calloc or realloc
sarko Function P732 ·# include< unistd. h> void* sbrk(int incr) If successful It returns the old value of brk If unsuccessful · It returns-1 · It sets errno to nomen If incr is zero It returns the current value incr can be a negative number
7 sbrk() Function P732 • #include <unistd.h> • void *sbrk(int incr) – If successful • It returns the old value of brk – If unsuccessful • It returns –1 • It sets errno to ENOMEM – If incr is zero • It returns the current value – incr can be a negative number
Assumptions Assumptions made in this lecture memory is word addressed (each word can hold a pointer) Free word Allocated block Free block (4 words) 3 words) Allocated word
8 • Assumptions made in this lecture – memory is word addressed (each word can hold a pointer) Allocated block (4 words) Free block (3 words) Free word Allocated word Assumptions
Allocation examples pl malloc(4) p2 malloc(5) 3=ma11oc(6) free(p2) p4 malloc(2) Figure 10.36 P733
9 p1 = malloc(4) p2 = malloc(5) p3 = malloc(6) free(p2) p4 = malloc(2) Allocation examples Figure 10.36 P733
10.9.2 Why Dynamic Memory Allocation
10 10.9.2 Why Dynamic Memory Allocation