Is the gets() string function in C considered a bad practice? [duplicate]

StackOverflow https://stackoverflow.com/questions/22419866

  •  15-06-2023
  •  | 
  •  

문제

was reading the Head first C book and stumbled across the author saying gets() to be a bad practice

gets() is a function that’s been around for a long time. But all you really need to know is that you really shouldn’t use it.

why is it considered a bad practice?

도움이 되었습니까?

해결책

Consider

#include<stdio.h>
int main()
{
    char buffer[100];
    gets(buffer);
    printf("The input is %s",buffer);
}

When user types input of length within 99 then there is no problem. But when user types more than 99 characters it tries to write into memory it doesn't own.

The worst thing is it causes abnormal behaviour and the program terminates without any information which leaves user baffled about the current situation

An alternative way is to use char *fgets(char *s, int size, FILE *stream); function

Update: As pointed by @pmg : gets() removes newline while fgets() retains the new line

다른 팁

gets is prone to buffer overruns (i.e. memory corruption etc).

fgets over comes this by having passing in the size of the buffer

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top