Magic numbers when debugging with gcc/g++/gdb/valgrind?

微笑、不失礼 提交于 2020-01-02 09:19:40

问题


Microsoft's Visual C++ fills memory with 'magic numbers' if it hasn't been initialized by the programmer itself. This helps with debugging of uninitialized memory. (In Visual Studio C++, what are the memory allocation representations?, 0xDEADBEEF vs. NULL)

Is there a similar function when using linux GNU tools (g++/gdb)?

Thanks!


回答1:


You can override the C++ operator new to set allocations to your preferred byte pattern:

void* operator new(size_t size)
{
    void* mem = malloc(size);
    if (!mem) {
        throw std::bad_alloc();
    }
    memset(mem, 0xEE, size);
    return mem;
}

You can see the full GCC implementation here: https://github.com/gcc-mirror/gcc/blob/master/libstdc%2B%2B-v3/libsupc%2B%2B/new_op.cc in case you want to mirror it more closely.

That will work for anything using the default C++ allocators, but not for things using regular old malloc(). If you need to initialize memory from malloc() directly, you can override that too, but the mechanism to do it is different: you can use the linker's --wrap option to manipulate the symbol table and let you override malloc(). Then you don't need to overload operator new of course. The full approach is illustrated in an answer here: https://stackoverflow.com/a/3662951/4323



来源:https://stackoverflow.com/questions/37090156/magic-numbers-when-debugging-with-gcc-g-gdb-valgrind

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