简体   繁体   中英

Why is printf() printing out in this code?

This simple code is puzzling me - I am deliberately printing out more integers than I passed to printf. I expected an error. I got weird numbers - where are they coming from?

#include <stdio.h>
/* learn arrays */
void main(){
    int pout;
    pout = 6;
    printf("%i %i %i\n%i %i %i\n%i %i %i\n", pout);
}

One example of the output:

6 608728840 0
-885621664 -885543392 608728816
0 0 -889304251

The single digits do not change with repeated runs, but the large integers do.

It's one of printf string format vulnerability. You are trying to call more argument than there actually are, so printf takes whatever he can on the stack.

It was (and still is) very used to exploit programs into exploring stacks to access hidden information or bypass authentication for example.

Viewing the stack

 printf ("%08x %08x %08x %08x %08x\\n"); 

This instructs the printf-function to retrieve five parameters from the stack and display them as 8-digit padded hexadecimal numbers. So a possible output may look like:

40012980 080628c4 bffff7a4 00000005 08059c04

See this for a more complete explanation.

Because it's undefined behavior. If the number of specifiers is larger than the number of matching parameters or their types are incompatible, the behavior is undefined.

This qoute is from the c11 standard draft

7.21.6.1 The fprintf function

  1. The fprintf function writes output to the stream pointed to by stream, under control of the string pointed to by format that specifies how subsequent arguments are converted for output. If there are insufficient arguments for the format, the behavior is undefined . If the format is exhausted while arguments remain, the excess arguments are evaluated (as always) but are otherwise ignored. The fprintf function returns when the end of the format string is encountered.

  1. If a conversion specification is invalid, the behavior is undefined. 282) If any argument is not the correct type for the corresponding conversion specification, the behavior is undefined .

I highlighted the relevant parts making them bold.

int保留了一些RAM,但是您没有写任何东西,因此它向您显示RAM中某处随机的数字

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM