0
votes

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?

2

2 Answers

3
votes

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);
0
votes

free don't need to know the number of bytes,just use it as 'Jonathon Reinhart' said.There is a simple implementation of malloc and free in chapter 8 in TCPL.Just read it,and you will know how free works without knowing the size of you dynamic allocated memory.Hope it works!