Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Memory consumption by printf( )

Tags:

c++

c

Does displaying a simple statement in C (or C++) occupy some memory? For example,

//in C
printf("\nHello World");
//in C++
cout<<"Hello World" ;

and, will it make a difference if I attach some value of a variable to be displayed in the same statement? For example,

printf("Value is %d" , var) ; 
like image 361
CodeBlaster Avatar asked Dec 05 '13 19:12

CodeBlaster


1 Answers

Code occupies memory. String literals occupy memory. Function calls (usually) use some stack.

Generally speaking I don't think printf should need to perform any dynamic memory allocations in order to work. But although (I believe) it's possible to avoid it I don't think they're forbidden from doing so. The same goes for cout << when outputting the types that have built-in support. If it ends up calling a user-defined overload then that can use whatever memory it likes.

Posix lists ENOMEM as a possible error for printf but not for snprintf. This suggests that on Posix systems (which of course is not all C implementations) the output might dynamically allocate memory, but the formatting will not.

like image 180
Steve Jessop Avatar answered Oct 14 '22 20:10

Steve Jessop