关于获取(c)中 [英] About gets() in C
问题描述
我写一个C程序,其中有5个元素的数组存储字符串。而且我在使用得到()
以获取输入。当我超过5个字符输入,然后输出字符串,它只是给了我所有的我。我知道该字符串由 \\ 0
所以即使终止键入的字符我超出了我的阵列,它仍将输出整个事情。
I am writing a C program, which has a 5-element array to store a string. And I am using gets()
to get input. When I typed in more than 5 characters and then output the string, it just gave me all the characters I typed in. I know the string is terminated by a \0
so even I exceeded my array, it will still output the whole thing.
但我很好奇是哪儿获得()
存储输入,无论是缓冲区,或者只是直接进入我的数组?结果
如果我在很长很长的字符串类型,则获得()
试图在回忆中存储字符不应该被感动?将它给了我一个段的错吗?
But what I am curious is where exactly gets()
stores input, either buffer or just directly goes to my array?
What if I type in a long long string, will gets()
try to store characters in the memories that should not be touched? Would it gives me a segment fault?
推荐答案
这就是为什么获得
是恶。它不检查数组边界,经常调用的未定义行为即可。切勿使用获得
,而是可以使用 与fgets
。结果
顺便说一句,现在获得
不再被C.的一部分,它已经在C11标准中删除,取而代之的是新的安全替代的, gets_s
1 (请参见维基一>)。因此,最好忘掉获得
。
That's why gets
is an evil. It does not check array bound and often invokes undefined behavior. Never use gets
, instead you can use fgets
.
By the way, now gets
is no longer be a part of C. It has been removed in C11 standard in favor of a new safe alternative, gets_s
1 (see the wiki). So, better to forget about gets
.
<分> 1。 C11:K.3.5.4.1的 gets_s
函数
<分> 简介
#define _ _STDC_WANT_LIB_EXT1_ _ 1
#include <stdio.h>
char *gets_s(char *s, rsize_t n);
这篇关于关于获取(c)中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!