jameshfisher jameshfisher - 1 year ago 58
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

. 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
! One source tells me I should actually use
: "You use
when you are counting something, and are sure that it cannot be negative."

I'm not so sure.
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
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
, or a pointer type, or something else?

Answer Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download