开发者

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

Will开发者_StackOverflow中文版 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.


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.


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
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜