URI:
   DIR Return Create A Forum - Home
       ---------------------------------------------------------
       techsuns
  HTML https://techsuns.createaforum.com
       ---------------------------------------------------------
       *****************************************************
   DIR Return to: Puzzles && Algorithms
       *****************************************************
       #Post#: 6--------------------------------------------------
       Different malloc
       By: kranthipls Date: August 6, 2012, 11:14 am
       ---------------------------------------------------------
       Write an aligned malloc & free function that takes number of
       bytes and aligned byte
       (which is always power of 2)
       EXAMPLE
       [glow=blue,2,300]align_malloc (1000,128) will return a memory
       address that is a multiple of 128 and
       that points to memory of size 1000 bytes.
       aligned_free() will free memory allocated by align_malloc[/glow]
       #Post#: 46--------------------------------------------------
       Re: Different malloc
       By: kranthipls Date: August 22, 2012, 10:45 am
       ---------------------------------------------------------
       We will use malloc routine provided by C to implement the
       functionality.
       Allocate memory of size (bytes required + alignment – 1 +
       sizeof(void*)) using malloc.
       alignment: malloc can give us any address and we need to find a
       multiple of align-
       ment.
       (Therefore, at maximum multiple of alignment, we will be
       alignment-1 bytes away
       from any location.)
       sizeof(size_t): We are returning a modified memory pointer to
       user, which is different
       from the one that would be returned by malloc. We also need to
       extra space to store
       the address given by malloc, so that we can free memory in
       aligned_free by calling
       free routine provided by C.
       2.
       return NULL.
       3.
       alignment (call this p2).
       4.
       size_t bytes ahead of p2), which
       will be required by aligned_free.
       5.
       CODE:
       1
       {
       2
       3
       4
       5
       6
       7
       8
       9
       10
       11
       12
       13
       14
       p2 = (void**)(((size_t)(p1) + offset) & ~(alignment - 1));
       
       p2[-1] = p1;
       
       return p2;
       }
       void aligned_free(void *p) {
       
       free(((void**)p)[-1]);
       }
       *****************************************************