gets() function and '\\0' zero byte in inp

2020-03-30 05:41发布

问题:

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.

回答1:

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


标签: c glibc libc gets