I want to know which C standard library functions use malloc
and free
under the hood. It looked to me as if printf
would be using malloc
, but when I tested a program with valgrind
, I noticed that printf
calls didn't allocate any memory using malloc
. How come? How does it manage the memory then?
Usually, the only routines in the C99 standard that might use malloc()
are the standard I/O functions (in <stdio.h>
where the file structure and the buffer used by it is often allocated as if by malloc()
. Some of the locale handling may use dynamic memory. All the other routines have no need for dynamic memory allocation in general.
Now, is any of that formally documented? No, I don't think it is. There is no blanket restriction 'the functions in the library shall not use malloc()
'. (There are, however, restrictions on other functions - such as strtok()
and srand()
and rand()
; they may not be used by the implementation, and the implementation may not use any of the other functions that may return a pointer to a static memory location.) However, one of the reasons why the extremely useful strdup()
function is not in the standard C library is (reportedly) because it does memory allocation. It also isn't completely clear whether this was a factor in the routines such as asprintf()
and vasprintf()
in TR 24731-2 not making it into C1x, but it could have been a factor.
The standard doesn't place any requirements on the implementation, AFAIK.
I don't know exactly how printf
is implemented, but of the top of my head, I can't think of a reason why it would need to dynamically allocate memory. You could always look at the source for your platform.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With