Chris Smith
Chris Smith

Reputation: 3012

How to test if a number ends in a value?

I have a memory leak in my program. I have replaced all calls to malloc (and new) 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 0x10c10 and the next time, it may be 0x20c10. 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.

Upvotes: 2

Views: 421

Answers (1)

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726929

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.

Upvotes: 4

Related Questions