简体   繁体   中英

scanf and printf not printing right values

What is going on here? The code goes like:

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

int main()
{
    char name[15];
    char name_[15];
    char answ[1];

    printf("What's your name?\n");
    scanf("%s", name);

    strcpy(name_, name);

    printf("Yes / No: ");
    scanf("%s", answ);

    printf("Hello! %s\n", name_);
    printf("You said: %s\n", answ);

    return 0;
}

With input "name" and "yes" the expected output is that it says:

Hello! name

You said: yes

Instead I get:

Hello! es

You said: yes

I also tried adding spaces before %s with no results.

So what exactly am I missing here?

answ can contain only 1 character. So currently, the extra character "es" + '\0' gets written into the memory assigned to name_ . So, "es" gets printed.

You've only allocated space for a one-character yes/no answer, but are writing more characters into it.

This results in undefined behaviour .

You need to allocate more space for answ , not forgetting about the NUL terminator.

You have created a classic exploitable buffer overrun but in your code. This is why most modern compilers would advise you to swap sscanf to sscanf_s or similar. As other people have pointed out, you overwrite the next variable on the stack.

I wanted to provide this answer to basically say: never ever use sscanf or any of the obsolete, insecure C functions. Even if this is probably just a toy example, get the practice in to write modern C code. You'll benefit from this in the long run.

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