27.10.2014 Views

Cracking the Coding Interview, 4 Edition - 150 Programming Interview Questions and Solutions

Cracking the Coding Interview, 4 Edition - 150 Programming Interview Questions and Solutions

Cracking the Coding Interview, 4 Edition - 150 Programming Interview Questions and Solutions

SHOW MORE
SHOW LESS

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

<strong>Solutions</strong> to Chapter 16 | Low Level<br />

16.9 Write an aligned malloc & free function that takes number of bytes <strong>and</strong> aligned byte<br />

(which is always power of 2)<br />

EXAMPLE<br />

align_malloc (1000,128) will return a memory address that is a multiple of 128 <strong>and</strong><br />

that points to memory of size 1000 bytes.<br />

SOLUTION<br />

aligned_free() will free memory allocated by align_malloc.<br />

1. We will use malloc routine provided by C to implement <strong>the</strong> functionality.<br />

Allocate memory of size (bytes required + alignment – 1 + sizeof(void*)) using malloc.<br />

alignment: malloc can give us any address <strong>and</strong> we need to find a multiple of alignment.<br />

(Therefore, at maximum multiple of alignment, we will be alignment-1 bytes away<br />

from any location.)<br />

sizeof(size_t): We are returning a modified memory pointer to user, which is different<br />

from <strong>the</strong> one that would be returned by malloc. We also need to extra space to store<br />

<strong>the</strong> address given by malloc, so that we can free memory in aligned_free by calling<br />

free routine provided by C.<br />

2. If it returns NULL, <strong>the</strong>n aligned_malloc will fail <strong>and</strong> we return NULL.<br />

3. Else, find <strong>the</strong> aligned memory address which is a multiple of alignment (call this p2).<br />

4. Store <strong>the</strong> address returned by malloc (e.g., p1 is just size_t bytes ahead of p2), which<br />

will be required by aligned_free.<br />

5. Return p2.<br />

1 void* aligned_malloc(size_t required_bytes, size_t alignment) {<br />

2 void* p1; // original block<br />

3 void** p2; // aligned block<br />

4 int offset = alignment - 1 + sizeof(void*);<br />

5 if ((p1 = (void*)malloc(required_bytes + offset)) == NULL) {<br />

6 return NULL;<br />

7 }<br />

8 p2 = (void**)(((size_t)(p1) + offset) & ~(alignment - 1));<br />

9 p2[-1] = p1;<br />

10 return p2;<br />

11 }<br />

12 void aligned_free(void *p) {<br />

13 free(((void**)p)[-1]);<br />

14 }<br />

pg 82<br />

2 4 7<br />

<strong>Cracking</strong> <strong>the</strong> <strong>Coding</strong> <strong>Interview</strong> | Knowledge Based

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!