Why am I not able to use gets and puts in my c++ program? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 3

Why am I not able to use gets and puts in my c++ program?

I tried this simple program- #include <iostream> #include<string> #include<stdio.h> using namespace std; int main() { cout<<"enter your name\n"; char name[20]; gets(name); puts(name); return 0; } . it doesn't take user's input rather it prints some random characters itself. Can you please tell what mistake I am making?

4th Jun 2017, 3:09 PM
Rahul Prabhakar
Rahul Prabhakar - avatar
8 Answers
+ 15
That's correct @Rahul it varies on the implementation and version of the compiler, even possibly can between flavors of linux depending on what the maintainers choose, but i think the statement in that link is the mainstream direction.
4th Jun 2017, 5:58 PM
cyber33
cyber33 - avatar
+ 15
@Martin Taylor, thank you for mentioning since buffer overflow can occur, even allowing someone to overwrite the return() pointer to execute their own code: http://www.cprogramming.com/tutorial/secure.html. For a bit of history: http://insecure.org/stf/smashstack.html. in a security class we tried to mimic that bit of history but it was years after the paper was written and gcc had been patched it seems to prevent that but some folks have updated the process to make it work... regardless it's good for programmers to know these vulnerabilities can occur and what to do to avoid.
5th Jun 2017, 2:41 AM
cyber33
cyber33 - avatar
+ 14
see http://www.cplusplus.com/reference/cstdio/gets/ that it got removed from C library ... you might still be able to include <cstdio> the equiv of C include<stdio.h> but in cpp,
4th Jun 2017, 5:08 PM
cyber33
cyber33 - avatar
+ 4
Because you need data on the input pipe. This is a working gets() with a canary showing why gets() is unsafe: https://code.sololearn.com/clrkpx6TfU3S/?ref=app Canaries are used in production code for exactly this purpose and...you're getting garbage because you don't zero your input array.
15th Jun 2017, 4:26 PM
Kirk Schafer
Kirk Schafer - avatar
+ 2
I remember I have used these gets and puts in linux. May be it differs from compiler to compiler. Is it?
4th Jun 2017, 5:28 PM
Rahul Prabhakar
Rahul Prabhakar - avatar
+ 1
Dude This due to /n at end of your cout statement, remove /n It will work fine
4th Jun 2017, 3:22 PM
Kurian Benoy
Kurian Benoy - avatar
+ 1
No bro, it didn't work.
4th Jun 2017, 3:26 PM
Rahul Prabhakar
Rahul Prabhakar - avatar
+ 1
yeah, I had tried this and it worked. But then I wanted to use gets and puts. can't I?
4th Jun 2017, 4:44 PM
Rahul Prabhakar
Rahul Prabhakar - avatar