如果malloc通过gdb返回NULL,如何设置条件断点

Aar*_*ron 7 c linux malloc gdb

示例源代码:

#include        <stdio.h>
#include        <stdlib.h>
#include        <errno.h>

#define         GIGABYTE        1024*1024*1024

int
main (void)
{
        void    *foo;
        int     result;

        foo = (void *) malloc (GIGABYTE*5);
        result = errno;

        if (foo != NULL) {
                return 2;
        } else {
                fprintf (stderr, "ERROR: %d\n", result);
                return 1;
        }
        return 0;
}
Run Code Online (Sandbox Code Playgroud)

题:

  • 如何指导GDB( # gdb -silent ./huge_malloc)来停止/暂停执行,如果malloc()回报率0x0,没有检查是否foo0x0

Jes*_*ter 7

您可以识别malloc的出口点并在那里放置条件断点.如:

(gdb) tbreak main
Breakpoint 1 at 0x4005c4: file t.c, line 13.
(gdb) r
Starting program: /var/tmp/a.out 
main () at t.c:13
13          foo = malloc (64);
(gdb) br *__libc_malloc+211 if $rax==0
Breakpoint 2 at 0x7f26d143ea93
(gdb) n
14          foo = malloc (GIGABYTE*64);
(gdb) p foo
$1 = (void *) 0x21dc010
(gdb) n

Breakpoint 2, 0x00007f26d143ea93 in malloc () from /lib/libc.so.6
Run Code Online (Sandbox Code Playgroud)

注意,我已经添加了一个malloc成功的调用,以说明断点仅触发NULL返回值.断点地址可能随libc版本而变化,我通过逐步检查找到它malloc,nexti直到我按下ret指令.