Does realloc and calloc call malloc?

This is probably a simple question, but I could not find the answer. Is malloc internally called inside realloc and inside calloc? Since I am somehow counting the malloc calls, this is interesting to me. Thanks

+4
source share
4 answers

You should not try to depend on system, library, or compiler-dependent mechanisms. Even if you know that realloc calls malloc on one system / compiler / library, you cannot be sure 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, setting up a global replacement for the new and delete statements. On some versions of Linux, you can also add interceptors to malloc (never used this function). On other systems, you can use other mechanisms to achieve what you need more safely.

+6
source

Since you are working on Linux, you are probably using glibc. You can look at the source code of glibc malloc and see that it calls what is called __malloc_hook from functions such as calloc. This is a documentary function that you can use to intercept and count selections. You can get other useful statistics from mallinfo . But look if there is an existing tool that first selects what you want. Debugging and memory management statistics are a common requirement!

+2
source

You can write a simple test program that calls realloc and calloc and feeds them to callgrind (one of Valgrind's tools). It will display a call graph so you can check which functions call malloc and calloc in your libc implementation.

+1
source

We do not know by language standards. C99 says nothing about functions that call each other or not.

C ++ only says that malloc cannot call new , but it does not have other such restrictions for any function.

0
source

All Articles