+ 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?
10 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.
+ 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.
+ 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,
+ 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.
+ 2
I remember I have used these gets and puts in linux. May be it differs from compiler to compiler. Is it?
+ 1
Dude This due to /n at end of your cout statement,
remove /n
It will work fine
+ 1
No bro, it didn't work.
+ 1
yeah, I had tried this and it worked. But then I wanted to use gets and puts. can't I?