J.Doe
J.Doe

Reputation: 319

Something wrong with printf or something

I am reading some material about safe programming,When I enter : ./a.out %.622496x%.622496x%n

./a.out %..622496x%n

./a.out %.633x%.63336x%n

./a.out %.6edd33x%.63336x%n

Some will got coredump some will not,can't figure out why they print all the 0.

Here is the code example.c gcc example.c

#include <stdio.h>
#include <string.h>

int main(int argc,char *argv[])
{
    char buffer[512]="";
    strncpy(buffer,argv[1],500);
    printf(buffer);

    return 0; 
}

Upvotes: 2

Views: 71

Answers (1)

Matthieu Brucher
Matthieu Brucher

Reputation: 22023

You have to sanitize your inputs before displaying such a string.

As you have %xxx is the string, printf interpret these as potential arguments, and then will try to get them, hence the core dump. But this gets further, as this can mean security attacks through this mechanism. In a way, this is the C equivalent of SQL injections.

As @TypeIA, the proper way to do so is to consider buffer as an argument to the formatting string (printf("%s", buffer)), not the formatting string itself. This is also a reason why some compilers would warn if you create a function with arguments ( char * format, ... ); (not const).

Upvotes: 5

Related Questions