本文介绍了c:gets()和fputs()是危险函数吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在学校的计算机实验室中,我们使用 fputs 编写了一个程序,编译器返回了一个错误 gets是一个危险的函数,使用和类似的错误为 fputs


,但是在我输入这段代码时在家里:

In the computer lab at school we wrote a program using fputs and the compiler returned an error gets is a dangerous function to use and a similar error for fputs

but at home when i type in this bit of code:

#include <stdio.h>
main()
{
    FILE *fp;
    char name[20];
    fp = fopen("name.txt","w");
    gets(name);

    fputs(name,fp);
    fclose(fp);
}

我从来没有遇到过任何错误。在学校里的人和这个人很相似,只是有点冗长而且有更多的变数。

我在家使用codeblocks,在学校使用fedora默认的gcc。

这可能是编译器的问题吗?

i get no errors what so ever. The one at school was similar to this one, just a bit lengthy and having more variables.
I use codeblocks at home and the default gcc provided with fedora at school.
Could it be a problem with the compiler?

推荐答案

使用获取您需要准确知道您将读取多少个字符,并相应地使用足够大的缓冲区。如果使用的缓冲区小于读取的文件内容,则最终会超出分配的缓冲区的范围,导致未定义行为和无效程序。

With gets you need exactly know how many characters you will read and accordingly use a large enough buffer. If you use a buffer which is lesser than the contents of the file you read, you end up writing beyond the bounds of your allocated buffer and this results in an Undefined Behavior and an Invalid program.

相反,您应该使用 fgets ,它允许您指定要读取的数据量。

Instead you should use fgets which allows you to specify how much data to read.

您不会收到任何错误,因为您分配的缓冲区很可能 name 足够容纳您的文件内容 name.txt ,但如果它不是那么它的问题,因此编译器发出警告。

You don't get any errors because most likely your allocated buffer name is big enough to hold the contents of you file name.txt but if it was not then its a problem and hence the compiler issues the warning.

这篇关于c:gets()和fputs()是危险函数吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-02 04:26