Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Which C standard library functions use malloc under the hood

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?

like image 390
MetallicPriest Avatar asked Dec 12 '11 16:12

MetallicPriest


2 Answers

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.

like image 150
Jonathan Leffler Avatar answered Nov 15 '22 19:11

Jonathan Leffler


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.

like image 35
Oliver Charlesworth Avatar answered Nov 15 '22 19:11

Oliver Charlesworth