본문 바로가기
프로그래밍 언어/C,C++

C/C++ gets() 행 읽기 함수

by pagehit 2021. 7. 4.
반응형
#include <stdio.h>
char *gets(char *buffer);

 

gets() 함수는 표준 입력 스트림 stdin으로 행을 읽고 buffer에 저장한다. 함수가 행을 읽은 경우 개행 문자 \n을 null 문자 \0으로 대체한다.

gets()를 사용하지 말고, fgets()를 사용하자.
gets() 함수는 2011 standard에서 deprecated 되었고, 2014 standard에서 제거되었다. gets() 함수를 사용하는 것이 버퍼 오버플로우를 발생시킬 수 있는 위험이 있기 때문이다. gcc를 이용해 컴파일 할 경우 다음과 같은 경고 메시지가 나타난다: warning: the `gets' function is dangerous and should not be used. 


반환값

함수 호출이 성공한 경우 입력 받은 표준 스트림을 반환, 오류가 발생하거나 읽은 문자가 없는 경우 NULL 포인터를 반환. 오류가 있는 경우 buffer에 저장되는 값을 정의하지 않음. 파일의 끝 EOF인 경우 buffer가 변경되지 않음.


코드 예시

#include <stdio.h>

int main(void)
{
    char line[100];
    char *result;
    
    printf("Enter a string:\n");
    if ((result = gets(line)) != NULL)
        printf("Input string is: %s\n", line);
    else if (ferror(stdin))
        perror("Error");
}

 


[1] https://stackoverflow.com/questions/1694036/why-is-the-gets-function-so-dangerous-that-it-should-not-be-used

[2] https://stackoverflow.com/questions/68241957/why-does-it-occur-segmentation-fault-when-using-the-return-value-of-function-get/68242055#68242055

 

반응형

댓글