How to use mcheck for Heap Consistency Check in GNU C?

拥有回忆 提交于 2019-12-08 10:39:52

问题


I am trying to understand how heap consistency checking works in GNU C Library. I Refered http://www.gnu.org/software/libc/manual/html_node/Heap-Consistency-Checking.html#Heap-Consistency-Checking

Here is a sample program I have written. I expected as suggested in the manual if I run in gdb and call mcheck(0) my custom abortfn would be called. But it isn't getting called.

What am I missing here?

included necessary headers.

void *abortfn(enum mcheck_status status)
{
    switch(status) {
    case MCHECK_DISABLED:
            printf("MEMCHECK DISABLED\n");
            break;
    default:
            printf("MEMCHECK ENABLED\n");
    }
}

int main()
{
    printf("This is mcheck testing code\n");
    int *a = (int *) malloc(sizeof(int));
    *a = 10;
    printf("A: %d\n", *a);
    free(a); 
    return 0; 
}

回答1:


Today, compiling with all warnings & debug info (gcc -Wall -Wextra -g) then using valgrind is more convenient.

However, the very documentation that you are linking to says:

it is too late to begin allocation checking once you have allocated anything with malloc

So start your main as

 int main() {
   mcheck(abortfn); 

However, your abortfn should return void so code it as:

 void abortfn(enum mcheck_status status) {                                  
   switch(status) {                                                        
    case MCHECK_DISABLED:                                           
        printf("MEMCHECK DISABLED\n");                 
        break;                               
    default:                             
        printf("MEMCHECK ENABLED\n");                    
} }                                                                


来源:https://stackoverflow.com/questions/28529620/how-to-use-mcheck-for-heap-consistency-check-in-gnu-c

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!