Chris Smith Chris Smith - 1 year ago 74
C++ Question

How to test if a number ends in a value?

I have a memory leak in my program. I have replaced all calls to

) with calls to my own function, which tracks allocated things. At the end of the program, I compare the things allocated at the beginning, and the ones at the end, to get the list of everything that is "leaking".

The end goal is to take the list of "leaking" locations, and put them in an array. Every time something is allocated, it is checked against the list of "leaking" addresses, and if there is a match, it calls a special function which I can then set a breakpoint on (where I can then figure out which objects are leaking and deal with them appropriately).

The problem is, the first few parts of the address changes each time the program runs. For example, the first time, one "leaking" address would be
and the next time, it may be
. The last few digits are always the same, but the first few are not.

Is there a way I can compare only the last few digits? I was thinking using mod, but I wasn't able to come up with anything that worked. These are regular integers, not strings or anything.

Answer Source

You can compare the last N digits of a hex number by applying bitwise & operator to it with a mask representing the number of digits that you wish to compare. For example, to compare the last three hex digits, apply a mask of three Fs, like this:

uintptr_t a = ...
uintptr_t b = ...
if ((a&0xFFF) == (b&0xFFF)) {

You could also check XOR of the numbers for zeros in the last N digits, like this:

if ((a^b)&0xFFF == 0) {

With this said, your overall approach is probably sub-optimal, because memory profilers, such as valgrind, let you detect memory leaks without jumping through hoops with address manipulation.

If for some reason a homegrown profiling is the only way to go, you could use special macros for retrieving source file locations, and save them in a hash table along with addresses of leaked locations. This would let you go back to the place in the source code responsible for allocation without manipulating addresses at all.

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