Search code examples
cdata-structuresheap-memoryfree

Creating a heap in C with arbitrary node types. How to free it?


Asking for a sanity check on this design choice.

I'm writing a heap sort in C by creating a heap data structure that can accept node types of string or numerical. (I'm creating my own private heap that I can sort)

The nodes in the heap are void*, which are dereferenced to perform the comparison operations. The Heap struct stores the sizeof each node in Heap.nodesize, or -1 if the node is a string.

When a node is inserted, memory is allocated for the void*. If the Heap.nodesize is -1, strlen(val) is passed to malloc, otherwise Heap.nodesize is passed to malloc.

When performing comparisons, if Heap.nodesize is -1 strcmp is used, otherwise boolean operators are used for the numerical.

When the heap is freed, I plan to loop through and free each void*. At this point will free know how many bytes to free for each node?


Solution

  • You don't need to know the originally malloced size. You just pass the pointer that malloc() returned to free().

    ssize_t size = 400;
    void* p = malloc(size);
    // Do whatever with p
    free(p);