您的位置:首页 > 其它

gdb调试malloc-free 产生的coredown

2016-05-25 19:30 253 查看
1。将struct malloc_chunk内容破坏程序如下:

int fun0(const char *str)

{

    char buf[40];

    memset(buf, 0, sizeof(buf));

    strcpy(buf, str);

    ptrace("fun0");

    printf("fun0:%s\n", buf);

    char *tbuf1 = (char *)malloc(sizeof(char) * 4);

    char *tbuf2 = (char *)malloc(sizeof(char) * 4);

    strcpy(tbuf1 -4, str);

    strcpy(tbuf2, str);

    printf("fun1:%s\n", tbuf1);

    printf("fun2:%s\n", tbuf2);

    free(tbuf1);

    free(tbuf2);

    return 0;

}

如下gdb内容:

#0  0x00007fd5bcc67cc9 in __GI_raise (sig=sig@entry=6) at ../nptl/sysdeps/unix/sysv/linux/raise.c:56

#1  0x00007fd5bcc6b0d8 in __GI_abort () at abort.c:89

#2  0x00007fd5bcca4394 in __libc_message (do_abort=do_abort@entry=1, fmt=fmt@entry=0x7fd5bcdb2b28 "*** Error in `%s': %s: 0x%s ***\n")

    at ../sysdeps/posix/libc_fatal.c:175

#3  0x00007fd5bccb066e in malloc_printerr (ptr=<optimized out>, str=0x7fd5bcdb2c58 "double free or corruption (out)", action=1)

    at malloc.c:4996

#4  _int_free (av=<optimized out>, p=<optimized out>, have_lock=0) at malloc.c:3840

#5  0x0000000000400d6f in fun0 (str=0x400f56 "yangzhengwen") at mcore.cpp:46

#6  0x0000000000400dce in main (argc=1, argv=0x7ffd67472a88) at mcore.cpp:66

提示:两次 释放,其实是的指针结构被破坏了。

修改为如下:

    free(tbuf1);

    free(tbuf1);

    free(tbuf2);

core  down如上次,

修改为如下:

    free(tbuf1);

    free(tbuf2);

    free(tbuf1);

没有core down。说明了什么?

2. 申请内存与struct malloc_chunk的关系:

    char *tbuf1 = (char *)malloc(sizeof(char) * 4);

    char *tbuf2 = (char *)malloc(sizeof(char) * 4);

    char *tbuf3 = (char *)malloc(sizeof(char) * 40);

    char *tbuf4 = (char *)malloc(sizeof(char) * 1024);

gdb中:

(gdb) p  *((mchunkptr)((char*)(tbuf1) - 2*sizeof(size_t)))

$1 = {prev_size = 140737354127864, size = 33, fd = 0x0, bk = 0x0, fd_nextsize = 0x0, bk_nextsize = 0x21}

(gdb) p  *((mchunkptr)((char*)(tbuf2) - 2*sizeof(size_t)))

$2 = {prev_size = 0, size = 33, fd = 0x0, bk = 0x0, fd_nextsize = 0x0, bk_nextsize = 0x31}

(gdb) p  *((mchunkptr)((char*)(tbuf3) - 2*sizeof(size_t)))

$3 = {prev_size = 0, size = 49, fd = 0x0, bk = 0x0, fd_nextsize = 0x0, bk_nextsize = 0x0}

(gdb) p  *((mchunkptr)((char*)(tbuf4) - 2*sizeof(size_t)))

$4 = {prev_size = 0, size = 1041, fd = 0x0, bk = 0x0, fd_nextsize = 0x0, bk_nextsize = 0x0}

可见,mchunkptr的size比实际申请的要大一点。说明书上的内存管理 的分配算法。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: