简体   繁体   English

这个缓冲区溢出了吗?

[英]Is this buffer overflow?

Really confused if my program is behaving the way it's supposed to. 如果我的程序按照预期的方式运行,那真的很困惑。 this isn't homework, just a fun march madness predictor program I'm writing. 这不是家庭作业,只是一个有趣的三月疯狂预测计划我正在写作。

    char buffer[20];
    char team1_name[20];    // 18 chars + new line + null
    char team2_name[20];

    printf("Who is team 1?\n");
    fgets(buffer, sizeof(buffer), stdin);
    strncpy(team1_name, buffer, sizeof(team1_name));
    team1_name[strlen(team1_name) - 1] = '\0';

    printf("\nWho is team 2?\n");
    fgets(buffer, sizeof(buffer), stdin);
    strncpy(team2_name, buffer, sizeof(team2_name));
    team2_name[strlen(team2_name) - 1] = '\0';

    printf("\nEnter %s's info:\n", team1_name);

Out of curiosity I enter a team name greater than 20 characters and it completely skips over the second print statement. 出于好奇,我输入一个大于20个字符的团队名称,它完全跳过第二个打印语句。 am I protecting against buffer overflow? 我可以防止缓冲区溢出吗? is it up to the user to not put in something huge? 是不是因为用户没有放入巨大的东西? Do I need flush statements? 我需要刷新声明吗?

This is the output: 这是输出:

    Who is team 1?
    wjefowiejfwoiejfweoifjweoifjweofijweoifj

    Who is team 2?

    Enter wjefowiejfwoiejfwe's info:
    Wins in last 12:

    Losses in last 12:

    Points per game:

The problem is that, since your input is truncated in the first fgets (you have more than 20 chars), then the second fgets will read the end of the FIRST input string from stdin. 问题在于,由于您的输入在第一个fgets中被截断(您有超过20个字符),因此第二个fgets将从stdin读取FIRST输入字符串的结尾。

Display "team2_name" value to see it (it contains chars after the 20 first chars in team1_name). 显示“team2_name”值以查看它(它包含team1_name中20个第一个字符后面的字符)。

Oops, sorry, the following comment was wrong. 哎呀,对不起,以下评论错了。 Forget about it : And yes, fgets MUST use sizeof(buffer)-1, because this argument is the max number of chars read. 忘了它:是的,fgets必须使用sizeof(缓冲区)-1,因为这个参数是读取的最大字符数。 So if you read sizeof(buffer) chars, you will need sizeof(buffer)+1 chars to store them (including trailing '\\0') 因此,如果您读取sizeof(缓冲区)字符,则需要sizeof(缓冲区)+1字符来存储它们(包括尾随'\\ 0')

You read 20 chars out of stdin, but the rest of the input still remains in the stream. 你从stdin中读出20个字符,但其余的输入仍然保留在流中。 The next fgets reads those remaining chars, so Team1 is called wjefowiejfwoiejfwe and Team2 oifjweofijweoifj . 下一个fgets读取剩余的字符,因此Team1称为wjefowiejfwoiejfwe和Team2 oifjweofijweoifj Print Team2's name as well and you will see this is true. 打印Team2的名字,你会发现这是真的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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