5

Will the gets() function from C language (e.g. from glibc) stop, if it reads a zero byte ('\0') from the file ?

Quick test: echo -ne 'AB\0CDE'

Thanks.

PS this question arises from comments in this question: return to libc - problem

PPS the gets function is dangerous, but it is a question about this function itself, not about should anybody use it or not.

2
  • 2
    Note that you are not supposed to be using gets: stackoverflow.com/questions/1694036/… Feb 21, 2011 at 16:13
  • @Jeremiah Willcock, of course, but this question arises after a easiest stack overflow example, which uses gets to illustrate its dangerous (see linked Q).
    – osgx
    Feb 21, 2011 at 16:15

2 Answers 2

7

The behavior of gets() is that it stops when a newline character is encountered or if EOF is encountered. It does not care if it reads \0 bytes.

C99 Standard, 7.19.7.7

Synopsis

   #include <stdio.h>

   char *gets(char *s);

Description

The gets function reads characters from the input stream pointed to by stdin, into the array pointed to by s, until end-of-file is encountered or a new-line character is read. Any new-line character is discarded, and a null character is written immediately after the last character read into the array.

From GNU libc documentation: http://www.gnu.org/software/libc/manual/html_node/Line-Input.html#Line-Input

— Deprecated function: char * gets (char *s)

The function gets reads characters from the stream stdin up to the next newline character, and stores them in the string s. The newline character is discarded (note that this differs from the behavior of fgets, which copies the newline character into the string). If gets encounters a read error or end-of-file, it returns a null pointer; otherwise it returns s.

2

It will not stop at zero byte.

$ cat gets22.c
int main(int argc, char **argv) {
  char array[8];
  gets(array);
  printf("%c%c%c%c%c%c%c\n",array[0],array[1],array[2],array[3],array[4],array[5],array[6],array[7]);
  printf("%d %d %d %d %d %d %d\n",array[0],array[1],array[2],array[3],array[4],array[5],array[6],array[7]);
}

$ gcc gets22.c  -o gets22

$ echo -ne 'AB\0CDE'| ./gets22
ABCDE
65 66 0 67 68 69 0

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.