我正在编写一个小的C代码来接收一些用户输入,这将是一个字符串。现在我读了很多地方,使用gets()会非常不安全,因为它可能导致缓冲区溢出攻击。而在大多数地方,我发现作为一种替代方法是使用fgets(),而就缓冲区溢出而言更安全。调整gets()以避免缓冲区溢出
现在我有一个问题场景,我不知道之前的缓冲区大小。它不能确定。它可能是任何东西。所以在这种情况下,fgets()会很方便吗?
另外,如果我使用gets()来解决这个问题,那么会出现什么问题呢?
char * temp_buffer_to_hold_user_input = NULL;
cahr * actual_buffer_that_stores_user_input = NULL;
int length_of_user_input =0;
/* taking user input, irrespective of its length using gets() */
gets(temp_buffer_to_hold_user_input);
/* now finding the length of the user input string and allocating the required number of bytes for proper (safe) usage */
length_of_user_input=length(temp_buffer_to_hold_user_input);
actual_buffer_that_stores_user_input = (char*)malloc(length_of_user_input*sizeof(char));
strcpy(actual_buffer_that_stores_user_input, temp_buffer_to_hold_user_input);
/* and now we work with our actual buffer */
那么gets()的上述用法仍然存在缓冲区溢出问题?因为在上面我们没有首先声明一个固定大小的缓冲区......所以没有缓冲区溢出是我所期望的。
如果我错过了某些东西,请纠正我!
确实没有缓冲区溢出。 'gets()'将字符串存储在'NULL'处将会受到伤害。 – Quentin
只要说** NO **到'gets()'并且继续你的生活。仅供参考:自2011年12月以来,'gets()'不再是C语言的一部分(一些C2011编译器将其作为扩展提供;其他编译器可能不兼容C2011)。 – pmg
因为使用动态数组(char * temp_buffer_to_hold_user_input = NULL;),所以不会发生缓冲区溢出问题。我认为没有必要将i/p存储到另一个阵列。 – Sathish