Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can GDB help to find out when a memory address is freed?

Tags:

c

gdb

Can GDB track when a memory address is freed? Putting a watch on the address doesn't help, since it does not break when memory at address is freed, but only when it is touched.

I think by using free(), only the pointer to the memory is freed, but the contents can still exist, until it is used by another memory allocation function.

(gdb) p (char *)0xee20229c
$2 = 0xee20229c "XYZ"
(gdb) watch *(char *)0xee20229c
Hardware watchpoint 3: *(char *) 3995083420
(gdb) c
Continuing.
...
...
Hardware watchpoint 3: *(char *) 3995083420

Old value = 88 'X'    // Changes only when the contents are overwritten,
New value = 0 '\0'    // but not when the memory location '0xee20229c' is freed.
like image 910
adizone Avatar asked Oct 01 '22 20:10

adizone


1 Answers

Can GDB track when a memory address is freed?

In general, no. However, if you know something about the malloc and free being used, then yes.

Putting a watch on the address doesn't help, since it does not break when memory at address is freed, but only when it is touched.

That is correct.

I think by using free(), only the pointer to the memory is freed,

A pointer can't be freed. A block of memory that the pointer points to is freed.

but the contents can still exist, until it is used by another memory allocation function.

Correct.

So, if you want to know when 0xee20229c is being freed, and you know nothing about your malloc implementation, then the only way to solve this is with conditional breakpoint on free.

but for condition I would need to specify the exact argument passed to free(), which might not be the same name across functions.

I am not sure what you mean. The condition you want is: the address being free'd is 0xee20229c

Setting this condition may require that you have debug info available for your libc, or that you specify it via registers (you'll need to know the ABI for your platform).

What if you do know something about malloc?

Many malloc implementations keep "housekeeping" info just before the heap block. If your implementation does, then setting a watchpoint on address-of-interest - 4 or - 8 may get you desired result.

like image 117
Employed Russian Avatar answered Oct 11 '22 02:10

Employed Russian