警告:`gets'函数很危险,不应该使用[重复]

问题描述 投票:1回答:1

嗨,当我在终端上写make时,我收到此消息。 get有什么问题?我必须改变一些东西吗?感谢您的帮助。

user@ubuntu:~/Desktop/Project$ make
gcc -g -ansi -pedantic -Wall -lm project.o -o project 
project.o: In function `main':
project.c:(.text+0x2c8c): warning: the `gets' function is dangerous and should not be used.
void main(){
    char File_Name[55] = { "\0" };
    printf("Give Me File Name:\n");
    gets(File_Name);
    strcat(File_Name, ".as");
    Read_From_File(File_Name);
    printf("\n*******************************************\n");
    free_malloc();
}

c fgets c-strings gets
1个回答
1
投票

函数gets是不安全的,C标准不支持。使用的数组可以覆盖超出其大小的范围。而是使用功能fgets。那不是这个声明

gets(File_Name);

至少写像

fgets( File_Name, sizeof( File_Name ), stdin );

该函数可以将新行字符'\ n'附加到输入的字符串中。要删除它,请使用以下代码

#include <string.h>

//...

fgets( File_Name, sizeof( File_Name ), stdin );

File_Name[ strcspn( File_Name, "\n" ) ] = '\0';

考虑到此初始化

char File_Name[55] = { "\0" };

相当于

char File_Name[55] = "";

或到

char File_Name[55] = { '\0' };
© www.soinside.com 2019 - 2024. All rights reserved.