Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does printf know the length of the format argument?

int printf (const char* format, ... );

This is the signature of printf. What I don't understand is, how does printf know the length of the first argument (the const char* format).

It knows the start (because it's a pointer, I get that), but pointers don't have an end or something. Usually when you want to print something you must give a length (For example, Linux's sys_write) so how does printf know?

Edit:

I've been looking through the code I wrote in ASM a little more and I think it just looks for a \0 char. Is that correct?

like image 897
MasterMastic Avatar asked Dec 15 '22 12:12

MasterMastic


1 Answers

It is a null-terminated string (like all strings in C), so the first ASCII NUL ('\0' or plain 0) byte indicates the end of the string.

If you have a string "meow" in C it actually uses 5 bytes of memory which look like this in memory. The \0 is obviously a single byte with the value 0.

meow\0

In case you wonder how an actual '0' digit would be represented: The numbers 0..9 have the ASCII values 48..57, so "me0w" would have 48 byte at its third position.

like image 172
ThiefMaster Avatar answered Jan 06 '23 23:01

ThiefMaster