为什么我没有获得一个链接错误,当我为我自己的malloc和free? [英] Why don't I get a link error when I provide my own malloc and 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
inlibc.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 ownmalloc
andfree
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 implementrealloc
, and likelycalloc
andmemalign
andposix_memalign
. Otherwise, you'll get a mixture of implementations, and when someone passesrealloc
ed pointer to yourfree
, things will likely explode.这篇关于为什么我没有获得一个链接错误,当我为我自己的malloc和free?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!