导航:[首页]->[cpp]->[使用mcheck检测内存错误]

设置环境变量

#include <stdio.h>

int main(int argc, char * argv[])
{
    const char * src = "mcheck test";
    char * ptr = (char *)malloc(sizeof(char) * 32);
    memcpy(ptr, src, strlen(src));
    ptr[32] = '\0';  
    printf("*ptr=%s\n", ptr);                                                                                                              

    free(ptr);
    ptr = NULL;
    printf("process end\n");

    return 0;
}

~/test <root@debian> 11:46:33 $ ./a.out 
*ptr=mcheck test
process end
~/test <root@debian> 11:46:34 $ MALLOC_CHECK_=1 ./a.out 
*ptr=mcheck test
*** glibc detected *** ./a.out: free(): invalid pointer: 0x0828c008 ***
process end
~/test <root@debian> 11:46:43 $ MALLOC_CHECK_=2 ./a.out 
*ptr=mcheck test
Aborted

链接库mcheck

gcc main.c -lmcheck

~/test <root@debian> 11:50:03 $ ./a.out 
*ptr=mcheck test..........
memory clobbered past end of allocated block
Aborted

直接加入函数mcheck

#include <stdio.h>

int main(int argc, char * argv[])
{
    mcheck(NULL);                                                                                                                          
    const char * src = "mcheck test";
    char * ptr = (char *)malloc(sizeof(char) * 32);
    memcpy(ptr, src, strlen(src));
    ptr[32] = '\0';  
    printf("*ptr=%s\n", ptr);

    free(ptr);
    ptr = NULL;
    printf("process end\n");

    return 0;
}

~/test <root@debian> 11:50:55 $ ./a.out 
*ptr=mcheck test..........
memory clobbered past end of allocated block
Aborted

参考

  1. http://www.csdn123.com/html/blogs/20130828/60380.htm
  2. http://man7.org/linux/man-pages/man3/mcheck.3.html
  3. http://www.gnu.org/software/libc/manual/html_node/Heap-Consistency-Checking.html