Finding an index from an address



Hi

I have a heap of n objects of size Heap->ElementSize;

I receive from the client program an element to free, so
I have to put it in the free list. Since the heap is
just an array of n * ElementSize bytes, I find out
the index of the element to free from its address, then set
the bit to 1 to mark it as a free element.

Do you see anything wrong with this code?


static int AddToFreeList(ContainerHeap *heap,void *element)
{
char *p = heap->Heap;
char *elem = element;
size_t idx,byte;

idx = elem-p; // get the distance in bytes
if (idx < 0) return -1; // element not in the heap
idx /= heap->ElementSize; // Now in element size units
if (idx > l->Capacity) return -1; // element is not in the heap


byte = idx/8; // The byte in the bit map

// Set the bit in the bitmap to 1.
l->FreeMap[byte] |= (1 << (idx%8));

// Update counters
heap->Used--;
heap->FreeCount++;
return 1;
}

Specifically it is OK to use size_t?
.



Relevant Pages

  • Re: Finding an index from an address
    ... jacob navia wrote: ... I have a heap of n objects of size Heap->ElementSize; ... I receive from the client program an element to free, ... then ptrdiff_t seems like the right choice for the type of idx. ...
    (comp.lang.c)
  • Re: Finding an index from an address
    ... On 05/21/12 09:40 AM, jacob navia wrote: ... I have a heap of n objects of size Heap->ElementSize; ... I receive from the client program an element to free, ... To my eye it would be clearer to use const for the pointers and initialise idx and byte where they are used: ...
    (comp.lang.c)
  • Re: Finding an index from an address
    ... I have a heap of n objects of size Heap->ElementSize; ... I receive from the client program an element to free, ... char *elem = element; ... then I don't see how it can work as idx (and later ...
    (comp.lang.c)
  • Re: Question about grammar
    ... think it was called "bitmap" or something similar) that had a whole heap ... of very handy signs and symbols like that one. ... whizbang laptop that happens to have been supplied without it? ...
    (misc.writing)