PDA

View Full Version : 'gets' considered unsafe?




Soulstorm
Apr 17, 2005, 07:00 AM
Here is a sample code
#include <iostream>
#include <cstdio>

using namespace std;

int main(){
int t, i;
char text[100][80];

for (t=0; t<100; t++){
cout << t << "; ";
gets(text[t]);
if(!text[t][0]) break;
}
for (i=0; i<t; i++)
cout << text[i] << '\n';
return 0;
}
When I compile this code, although it compiles correctly, xCode gives me a message at the start of the executable file "warning: this program uses gets(), which is unsafe.". Why? Although I can run the program flawlessly, that warning bothers me, because don't know if this command will cause problems when I try to write other programs.

Oh, and how can I create a box that contains code in this forums? (you know, just like the box of a quote, but with code).



Mitthrawnuruodo
Apr 17, 2005, 07:26 AM
From C/C++ Programmers Reference: "There is no way to limit the number of characters that gets() will read, which means that the array pointed to by str could be overrun. Thus, this function is inherently dangerous. Its use should be limited to sample programs or utilities for your own use. It should not be used for production code."

Soulstorm
Apr 17, 2005, 11:53 AM
ok thanks! This "programmer reference"... What is it? Just another book?

Sorry if my question sounds newbish...

broken_keyboard
Apr 17, 2005, 12:17 PM
You can tell without the book. Look at the function call, you are passing an array without any indicator of it's size. How can the function possibly know how many chars are pointed to? There is no way.

The man page for gets recommends using fgets instead...

Mitthrawnuruodo
Apr 17, 2005, 12:44 PM
ok thanks! This "programmer reference"... What is it? Just another book?
Not, "just another book", but "The Most Authorative Quick Reference for C/C++ Programmers" (http://www.amazon.com/exec/obidos/ASIN/0072127066/ref=nosim/edazzlenet-20/002-9630226-4144816?dev-t=08FC0AFA9SSP0BEHY8G2), according to the Publisher... don't know about that, but it's VERY handy when programming and really cheap, too... ;)

GeeYouEye
Apr 18, 2005, 05:51 AM
WAY off topic, but...

soulstorm: your signature is inaccurate: iPods have 32 MB of RAM. ;)

Soulstorm
Apr 18, 2005, 01:55 PM
WAY off topic, but...

soulstorm: your signature is inaccurate: iPods have 32 MB of RAM. ;)
Didn't know that my iPod had RAM. Come to think of it, how it kept in its memory some songs to be played? Should have noticed it. Anyway, I fixed my sig. Thanks ;)

SilentPanda
Apr 19, 2005, 10:46 AM
To encapsulate code in this forum (and maybe others) you simply type CODE in the []'s instead of QUOTE.