c - -fno-builtin 的 MinGW gcc malloc 问题

标签 c gcc gdb mingw

我在 MinGW gcc 中遇到 malloc 和 free 的奇怪问题

最好用下面的程序来说明(注意没有外部头文件)

void free(void* p)
{
    write(1,"called free\n",12);
}
int main()
{
}

我正在使用以下命令进行编译: gcc -g -fno-内置测试.c

运行这个程序,我希望没有输出,但是当我运行这个程序时,我得到以下输出:

called free
called free
called free
called free

使用gdb,我发现free被调用了 mingwrt-4.0.3-1-mingw32-src\mingwrt-4.0.3-1-mingw32-src\src\libcrt\misc\glob.c

有没有办法关闭它?我原以为指定 -fno-builtin 会使我的程序无法调用 free 之类的东西

编辑: 我应该澄清一下,我已经用 malloc 和 free 编写了自己的内存库,问题是我不希望 MinGW 调用这些函数。我也不想使用任何外部库,如 stdio 或 stdlib。

我目前已经实现了重命名我的 malloc 和 free 的简单修复,但理想情况下我能够将它们命名为 malloc 和 free 而不必担心任何外部代码调用它们。如果有人也能解释为什么 MinGW 甚至需要在我上面编写的简单程序中 malloc 内存,我也会很感激。

最佳答案

您使用 -fno-builtin 标志的事实并不意味着编译器不会调用内置函数。

根据文档,这意味着编译器将为内置函数生成完整的函数调用,而不是使用特殊优化,如为函数生成代码。

来自 GCC 手册页:

Don't recognize built-in functions that do not begin with _builtin as prefix.

GCC normally generates special code to handle certain built-in functions more efficiently; for instance, calls to "alloca" may become single instructions which adjust the stack directly, and calls to "memcpy" may become inline copy loops. The resulting code is often both smaller and faster, but since the function calls no longer appear as such, you cannot set a breakpoint on those calls, nor can you change the behavior of the functions by linking with a different library. In addition, when a function is recognized as a built-in function, GCC may use information about that function to warn about problems with calls to that function, or to generate more efficient code, even if the resulting code still contains calls to that function. For example, warnings are given with -Wformat for bad calls to "printf", when "printf" is built in, and "strlen" is known not to modify global memory.

尽管可以覆盖mallocfree 的实现,但我认为唯一的方法是删除编译器添加到这些函数中以初始化程序环境的调用只能使用参数 -nostartfiles 删除。唯一的问题是,您将负责启动环境,因为编译器将不再为您提供它。

这篇文章有点跑题了,不过相信你可以在那里找到更多的答案和细节:

A Whirlwind Tutorial on Creating Really Teensy ELF Executables for Linux

关于c - -fno-builtin 的 MinGW gcc malloc 问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21486926/

相关文章:

c - C 程序中 fscanf 的奇怪行为

C++ ld 返回 1 退出状态

linux - "/usr/bin/ld: cannot find -lz"

c++ - 使用 GDB 获取 lambda 的行号

GDB 不以有符号十进制打印输出

c - 最有用的用户自定义 C 宏(在 GCC 中,也是 C99)?

javascript - 如何将大整数拆分为 8 位整数数组

c - 使用 Protocol Buffer 定义 MAC 地址

c++ - 无效的静态断言行为

debugging - 如何检查GDB中函数的返回值?