Why does this user introduce the fgets () function, causing the program to interrupt?

#include  <stdio.h>

int main()
{
    char buf[100];
    char s[100];
    int x = 1;
    fgets(s, 100, stdin);
    snprintf(buf, sizeof buf, s);
    printf("Buffer size is: (%d) \nData input: %s \n", strlen(buf), buf );
    printf("X equals: %d/ in hex: %x\nMemory address for x: (%p) \n", x, x, &x);
    return 0;
}

When I run this simple program c, the program starts execution, waits for stdin to enter, and then executes the print instructions. A.

Everything works fine, but when I enter '% n' in stdin, I get:

*** %n in writable segment detected ***
Aborted

What happens and why does this entry for fgets () call this?

+4
source share
1 answer

from https://linux.die.net/man/3/snprintf :

Code such as printf (foo); often indicates an error, since foo may contain the% character. If foo comes from unreliable user input, it may contain% n, causing the printf () call to be written to memory and creating a security hole.

snprintf - ( , ).

( %n, . % n C?), . ( ) , %n ( , C, )

, :

snprintf(buf,sizeof buf,"%s",s)
0

Source: https://habr.com/ru/post/1695945/


All Articles