'How to do an specific action when a certain breakpoint is hit in GDB?

I am looking for a way to do some action when a particular break point hits in gdb.

Basically I have some memleak in my program. When malloc and free function hits, I need to enter into the function (step) and collect some basic information like the addr and size (basically print there values). Once done resume my program.

Do we have any good way to do this?



Solution 1:[1]

To clarify Fredrik's answer, commands (or just command, it seems) automatically knows you just set a breakpoint. That is, what Fredrik is showing isn't a multi-line break command, it's two separate commands: break, and commands. It looks like this:

(gdb) break 989 
Breakpoint 23 at 0x7fffe2761dac: file foo.cpp, line 989.
(gdb) command
Type commands for breakpoint(s) 23, one per line.
End with a line saying just "end".
>silent
>print result
>end
(gdb) c
Continuing.
$79 = {elems = {0, 0}}
(gdb) 

Solution 2:[2]

dprintf (Dynamic printf)

https://sourceware.org/gdb/onlinedocs/gdb/Dynamic-Printf.html

This is the most convenient solution for the specific case of printing things:

dprintf <line>, "%u\n", variable

It could also be faster than commands as it could compile and inject code, instead of giving control back to GDB to interpret arbitrary command strings, which is extremely slow. TODO I don't know if this is actually done. dprintf vs commands: What is the difference between dprintf vs break + commands + continue?

Detailed example:

main.c

#include <inttypes.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>

int main(void) {
    uint32_t i;
    uint32_t r = 0;
    for (i = 0; i < 10; ++i) {
        r += i*i + 13*r*i + 17;   /* LINE 10. */
    }
    printf("%" PRIu32 "\n", r);
    return EXIT_SUCCESS;
}

Then:

gcc -ggdb3 -O0 -std=c99 -o main main.c
gdb -batch --nh -q -ex 'dprintf 10, "%u %u\n", i, r' -ex 'run' ./main

Output:

Dprintf 1 at 0x400545: file main.c, line 10.
0 0
1 17
2 256
3 6933
4 277346
5 14699371
6 970158528
7 3628079733
8 3070853710
9 317092431
3057168588
[Inferior 1 (process 14305) exited normally]

Tested in Ubuntu 16.04, GDB 8.2.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Ben
Solution 2 evandrix