- uint8_t* chunk_ptr = (uint8_t*)ptr - WSIZE;
- uint32_t hdr = LW(chunk_ptr);
- uint8_t* next_hdr = chunk_ptr + CHUNK_S(hdr);
-
- SW(chunk_ptr, hdr & ~M_ALLOCATED);
- SW(FPTR(chunk_ptr, CHUNK_S(hdr)), hdr & ~M_ALLOCATED);
- SW(next_hdr, LW(next_hdr) | M_PREV_FREE);
-
- coalesce(chunk_ptr);
-}
-
-void*
-coalesce(uint8_t* chunk_ptr)
-{
- uint32_t hdr = LW(chunk_ptr);
- uint32_t pf = CHUNK_PF(hdr);
- uint32_t sz = CHUNK_S(hdr);
- uint32_t ftr = LW(chunk_ptr + sz - WSIZE);
-
- uint32_t n_hdr = LW(chunk_ptr + sz);
-
- if (CHUNK_A(n_hdr) && pf) {
- // case 1: prev is free
- uint32_t prev_ftr = LW(chunk_ptr - WSIZE);
- size_t prev_chunk_sz = CHUNK_S(prev_ftr);
- uint32_t new_hdr = PACK(prev_chunk_sz + sz, CHUNK_PF(prev_ftr));
- SW(chunk_ptr - prev_chunk_sz, new_hdr);
- SW(FPTR(chunk_ptr, sz), new_hdr);
- chunk_ptr -= prev_chunk_sz;
- } else if (!CHUNK_A(n_hdr) && !pf) {
- // case 2: next is free
- size_t next_chunk_sz = CHUNK_S(n_hdr);
- uint32_t new_hdr = PACK(next_chunk_sz + sz, pf);
- SW(chunk_ptr, new_hdr);
- SW(FPTR(chunk_ptr, sz + next_chunk_sz), new_hdr);
- } else if (!CHUNK_A(n_hdr) && pf) {
- // case 3: both free
- uint32_t prev_ftr = LW(chunk_ptr - WSIZE);
- size_t next_chunk_sz = CHUNK_S(n_hdr);
- size_t prev_chunk_sz = CHUNK_S(prev_ftr);
- uint32_t new_hdr =
- PACK(next_chunk_sz + prev_chunk_sz + sz, CHUNK_PF(prev_ftr));
- SW(chunk_ptr - prev_chunk_sz, new_hdr);
- SW(FPTR(chunk_ptr, sz + next_chunk_sz), new_hdr);
- chunk_ptr -= prev_chunk_sz;