13

I am currently having to write implementations of malloc() and free(), and am given a driver program that will run my two implementations.

But currently, I am segfaulting because free() is trying to free a payload size that is well in the billions of bytes (which is wrong). I have the line and line number from running GDB, but I need to know if malloc() and free() have been called more than once, to confirm that there is indeed at least one case where it runs smoothly.

1
  • Well, I guess I could create a global variable in the program as a counter... and then print that in GDB. But is there a better method? Oct 20, 2011 at 3:53

4 Answers 4

18

First set a breakpoint for malloc and free. Afterwards use the "ignore" command with a high value to suppress really stopping at those breakpoints. GDB will still count how many times the breakpoints have been hit. When you call "info breakpoints", GDB will show you these counts.

18

Just to complete the information of Martin, run gdb and then, on the gdb prompt:

b <file:line_number or function name>
ignore <breakpoint identifier> 100000

Then you run your executable (or you resume) and then, when you want to check the number of times the breakpoint has been hit, on the gdb prompt:

info breakpoints
1

This is a good use case for a conditional breakpoint, where you can filter out calls that exceed your size threshold. Use the if (condition) clause in break.

Another option on linux is to use perf to set a probe and capture arguments. See perf probe for details. This lets you instrument the binary non-intrusively and trace all calls. perf script is good for outputting the results.

-6

(gdb) help break
Set breakpoint at specified line or function.
break [LOCATION] [thread THREADNUM] [if CONDITION]
LOCATION may be a line number, function name, or "*" and an address.
If a line number is specified, break at start of code for that line.
If a function is specified, break at start of code for that function.
If an address is specified, break at that exact address.
With no LOCATION, uses current execution address of selected stack frame.
This is useful for breaking on return to a stack frame.

1
  • 1
    The documentation of break is really good at documenting break but is not enough in this case :) . Martin's answer is the one that tells you how to see the hit count kept by GDB Sep 28, 2016 at 12:38

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.