为什么我没有获得一个链接错误,当我为我自己的malloc和free? [英] Why don't I get a link error when I provide my own malloc and free?

查看:130
本文介绍了为什么我没有获得一个链接错误,当我为我自己的malloc和free?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想实现一个简单的配合第一的内存管理算法。所以我有一个C文件与我自己

 的void * malloc的(为size_t)

 无效免费(无效*)

在生成 .OUT 用gcc文件,我期待一个链接错误,因为它会与现有的标准实现冲突。但我的文件链接的罚款。

请帮我明白了。


解决方案

  

我期待一个链接错误,因为它会与现有的标准实现冲突。


您的期望是不正确的:使用一些其他的malloc大多数UNIX的libc实现支持。为此,他们把的malloc 的realloc 免费等任一成一个单独的对象的文件,或者每到它自己的一个目标文件。

该链接器是免费的,然后用实现替换 malloc.o 的libc.a 。你可以阅读有关链接器使用 href=\"http://webpages.charter.net/ppluzhnikov/linker.html\">的算法。一旦你理解了算法,应该清楚为什么链接你自己的的malloc 免费不会导致链接错误。

UNIX共享库被明确设计模仿归档库,所以当你为什么用 libc.so 链接时没有得到一个链接错误的详细信息都不同,精神是一样的。

但是,你没有这样做。链接任何适度复杂的程序与实施,将有可能崩溃,因为当你更换的malloc ,您的需要实施的realloc ,并有可能释放calloc memalign可 posix_memalign 。否则,你会得到实现的混合物,当有人通过的realloc ED指向你的免费,事情会有可能引起爆炸。

I'm trying to implement a simple fit first memory management algorithm. So I've got a C file with my own

   void* malloc(size_t)

and

   void free(void*)

When generating a .out file with gcc, I'm expecting a link error because it'll conflict with the existing standard implementation. But my file links fine.

Please help me to understand.

解决方案

I'm expecting a link error because it'll conflict with the existing standard implementation.

Your expectation is incorrect: most UNIX libc implementations support using some other malloc. To that end, they put malloc, realloc, free etc. either into a separate object file, or each into an object file of its own.

The linker is then free to replace malloc.o in libc.a with your implementation. You can read about the algorithm the linker uses here. Once you understand the algorithm, it should be clear why linking your own malloc and free does not cause a link error.

UNIX shared libraries are explicitly designed to emulate archive libraries, so while details of why you don't get a link error when linking with libc.so are different, the spirit is the same.

However, you aren't done. Linking any moderately complicated program with your implementation will likely crash, because when you replace malloc, you also need to implement realloc, and likely calloc and memalign and posix_memalign. Otherwise, you'll get a mixture of implementations, and when someone passes realloced pointer to your free, things will likely explode.

这篇关于为什么我没有获得一个链接错误,当我为我自己的malloc和free?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆