jameshfisher jameshfisher - 10 days ago 5
C Question

What C type should I use to count objects in memory?

Let's say I want to keep track of how many allocations my program has made, so I increment/decrement a counter whenever I

malloc
or
free
. Similarly, I might want to count the length of a linked list.

What type should I use for such a value? I think the worst case for "number of objects in memory" is the number of bytes in the address space. That is, my counter should be the same size as a pointer type. This suggests I should set my counter as:

void * num_allocated_objects = 0;


However, this looks like an unconventional use of
void*
! One source tells me I should actually use
size_t
: "You use
size_t
when you are counting something, and are sure that it cannot be negative."


I'm not so sure.
size_t
is "used to represent the size of an object"
. These two answers seem incompatible: I can imagine a system in which the possible number of objects is larger than the size of the largest object in bytes. Using
size_t
to count things in memory must assume that the largest object in memory is the size of the entire address space.

What is the correct, idiomatic C type to count objects in memory? Is it
size_t
, or a pointer type, or something else?

Answer

If you want to be pedantic about this, then you should be using uintptr_t, which is an (unsigned) integer guaranteed large enough to hold a pointer value.

Therefore, you could in theory count every single addressable byte of memory with it. Not that you would, if you were counting actual objects in memory. But at least that unreachable upper-bound guarantees your data type is large enough.