Why don't I get a link error when I provide my own malloc and free?

。_饼干妹妹 提交于 2019-11-30 19:21:07

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.

In my experience, it is standard practice for custom mallocs and frees to be named uniquely, such as the kernel malloc, kmalloc, and kernel free, kfree. If you're writing your own, I recommend giving a separate name for your functions.

How are you planning to allocate memory? Most of the time you should wrap around the malloc function to provide custom functionality, but still end up using malloc in some form or another. In my opinion, this is the route you should take, so I wouldn't be too hasty to dispose of the built in malloc and free functions unless you have good reason (or strong desire) to do so. Having them named the same will interfere with this.

This is the Minix implementation of malloc, just to give you a sense of what you're looking at.

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