yui
yui

Reputation: 101

Does realloc and calloc call 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

Upvotes: 5

Views: 2915

Answers (4)

rptb1
rptb1

Reputation: 480

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!

Upvotes: 2

Bo Persson
Bo Persson

Reputation: 92341

We don't know from the languages standards. C99 says nothing about the functions calling each other, or not.

C++ only says that malloc can not call new, but has no other such restrictions on either function.

Upvotes: 0

LiKao
LiKao

Reputation: 10658

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.

Upvotes: 6

ovk
ovk

Reputation: 2358

You can write simple test program which calls realloc and calloc and feed it to callgrind (one of tools from Valgrind). It will show call graph so you can check what functions are called by malloc and calloc on your libc implementation.

Upvotes: 1

Related Questions