I am writing a small C code to take some user input, which would be a string. Now I read at a lot of places that using gets() will be very unsafe as it may lead to buffer overflow attacks. And in most of the places what I found as an alternative was using fgets() instead, which is safer as far as buffer overflows are concerned.
Now I have a problem scenario, where in I do not know the buffer size before hand. It just can not be determined. It could be anything. So in this case, will fgets() be handy ?
Also, what is wrong if I make use of gets(), as shown below, to solve this problem ?
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 */
So does the above usage of gets() still have buffer overflow problem ? Because, in the above we are not declaring a fixed size buffer at all in the first place... so no buffer overflow is what I am expecting.
Please correct me if I am missing out on something!

gets()storing the string atNULLwill hurt though.gets()and get on with your life. Just FYI:gets()is no longer part of the C language since December 2011 (some C2011 compilers provide it as an extension; other compilers may not be C2011 compatible yet).getlineorgetdeliminstead.