What is the difference between puts and printf in C compiled in assembly language

This is my C program using puts() :

 #include <stdio.h> int main(void){ puts("testing"); } 

After using gcc -S -o sample.s sample.c to compile it into Assembly, this is what I got:

  .file "sample.c" .section .rodata .LC0: .string "testing" .text .globl main .type main, @function main: pushl %ebp movl %esp, %ebp andl $-16, %esp subl $16, %esp movl $.LC0, (%esp) call puts leave ret .size main, .-main .ident "GCC: (GNU) 4.4.5 20110214 (Red Hat 4.4.5-6)" .section .note.GNU-stack,"",@progbits 

I did the same, this time I used printf() instead of puts, and this is what I got:

  .file "sample.c" .section .rodata .LC0: .string "testing" .text .globl main .type main, @function main: pushl %ebp movl %esp, %ebp andl $-16, %esp subl $16, %esp movl $.LC0, %eax //this is the difference movl %eax, (%esp) call printf leave ret .size main, .-main .ident "GCC: (GNU) 4.4.5 20110214 (Red Hat 4.4.5-6)" .section .note.GNU-stack,"",@progbits 

Here's what I don't understand, printf() function mov $.LC0 to %eax , then mov %eax to (%esp) , and function puts() mov %.LC0 directly on (%esp) . I do not know why this is.

+8
c assembly gcc
source share
1 answer

The big difference between the two functions at the assembly level is that the puts() function will take only one argument (pointer to the displayed string), and the printf() function will take one argument (pointer to the format string), and then any number of arguments on the stack ( printf() is a variational function).

Please note that there is absolutely no check on the number of arguments, it depends only on the amount of time at which the % character occurs in the format string. For example, this specificity is used in the method of using formatting format errors to interactively examine the contents of the process stack.

So, basically the difference is that puts() has only one argument, and printf() is a variational function.

If you want to better understand this difference, try compiling:

 #include <stdio.h> int main(void) { printf("testing %d", 10); } 
+4
source share

All Articles