What type should I use to count objects in C?
You often need to count objects in memory: for example, if you have a linked list, and you want to keep or calculate the length. What datatype should you use for this?
The right answer is
uintptr_t: the unsigned integral type which is guaranteed to be able to hold a pointer. Why? Because the worst case for “number of objects in memory” is that each object is a single byte, and they are packed into the entire address space. How many bytes are there in the address space? It’s exactly the largest possible pointer value. The smallest type capable of storing “the largest possible pointer value” is of course a pointer. But using a pointer as a counter is unconventional: we would be doing arithmetic with it. Instead, we use
uintptr_t, the integer value of the size as a pointer.
More by Jim
- Project C-43: the lost origins of asymmetric crypto
- How Hacker News stays interesting
- My parents are Flat-Earthers
- The dots do matter: how to scam a Gmail user
- The sorry state of OpenSSL usability
- I hate telephones
- The Three Ts of Time, Thought and Typing: measuring cost on the web
- Granddad died today
- Your syntax highlighter is wrong
I wrote this because I felt like it. This post is not associated with my employer. Found an error? Edit this page.