Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does realloc and calloc call malloc?

Tags:

c++

c

linux

malloc

This is probably an easy question but I couldn't find an answer. Is malloc internally called within realloc and within calloc? Since I am somehow counting the malloc calls, it is interesting for me. Thanks

like image 940
yui Avatar asked Jul 14 '11 14:07

yui


2 Answers

You should not try to depend on system, library or compiler dependent mechanisms. Even if you know realloc calls malloc on one system/compiler/library, you cannot be certain that it will be handled the same way on other systems.

The question at this point would be, what you are trying to achieve. If you need to track memory usage, there are better ways in C++, for example installing a global replacement for operators new and delete. In some versions of Linux you can also add hooks to malloc (never used this feature though). On other systems you can use other mechanisms to achieve what you need more safely.

like image 83
LiKao Avatar answered Oct 26 '22 06:10

LiKao


Since you are working on Linux you are probably using glibc. You can look at the glibc malloc source code and see that it calls something called __malloc_hook from functions like calloc. This is a documented feature you can use to intercept and count allocations. You can get other useful statistics from mallinfo. But see if there's an existing tool which achieves what you want first. Memory management debugging and statistics are a common requirement!

like image 43
rptb1 Avatar answered Oct 26 '22 05:10

rptb1