简体   繁体   English

使用 gcc/g++/gdb/valgrind 调试时的神奇数字?

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

Microsoft's Visual C++ fills memory with 'magic numbers' if it hasn't been initialized by the programmer itself.如果程序员自己没有初始化,微软的 Visual C++ 会用“幻数”填充内存。 This helps with debugging of uninitialized memory.这有助于调试未初始化的内存。 ( In Visual Studio C++, what are the memory allocation representations? , 0xDEADBEEF vs. NULL ) 在 Visual Studio C++ 中,内存分配表示是什么?0xDEADBEEF 与 NULL

Is there a similar function when using linux GNU tools (g++/gdb)?使用 linux GNU 工具 (g++/gdb) 时是否有类似的功能?

Thanks!谢谢!

You can override the C++ operator new to set allocations to your preferred byte pattern:您可以覆盖 C++ operator new以将分配设置为您的首选字节模式:

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.你可以在这里看到完整的 GCC 实现: https : //github.com/gcc-mirror/gcc/blob/master/libstdc%2B%2B-v3/libsupc%2B%2B/new_op.cc ,以防你想镜像它更紧密。

That will work for anything using the default C++ allocators, but not for things using regular old malloc() .这适用于使用默认 C++ 分配器的任何东西,但不适用于使用常规旧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() .如果您需要直接从malloc()初始化内存,您也可以覆盖它,但执行它的机制不同:您可以使用链接器的--wrap选项来操作符号表并让您覆盖malloc() Then you don't need to overload operator new of course.那么你当然不需要重载operator new The full approach is illustrated in an answer here: https://stackoverflow.com/a/3662951/4323完整方法在此处的答案中进行了说明: https : //stackoverflow.com/a/3662951/4323

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM