I'm making a file whose job is specifically to keep track of how many blocks I currently have allocated, as I don't want any memory leaks.
size_t BLOCKS_CURRENTLY_ALLOCATED = 0;
/* Since variables can be allocated in lots of different ways,
malloc, calloc, realloc, etc don't allocate here. Just mark down
how many bytes of memory was used for this value. */
void allocate(const void const *val)
{
BLOCKS_CURRENTLY_ALLOCATED += sizeof(*val);
}
/* Update the amount of blocks counter and free the pointer. */
void deallocate(const void const *val)
{
// Edit: I think I meant to do `sizeof(val)` but I don't know if that works
const size_t size = sizeof(*val);
if (BLOCKS_CURRENTLY_ALLOCATED < size)
exit(1); // Error, must have forgotten to report allocating.
free(val);
BLOCKS_CURRENTLY_ALLOCATED -= sizeof(size);
}
Is this code all legal? Am I able to use sizeof
to get the amount of blocks that were allocated for an unknown data type pointer that was at some point allocated with malloc
or calloc
? What about calling free
on a pointer whose data is const
and pointer is const
?