473,737 Members | 1,913 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

gets, fgets, scanf none is safe...

Hello all...
I can't remind which function to use for safe inputs...
gets, fgets, scanf leads to buffer overflow...

i compiled that code with gcc version 2.95.2, on windows 2000

char tmp0[10] = "ABCDEFGHI\ 0";
char buff[5]; /* Input buffer. */
char tmp1[10] = "ABCDEFGHI\ 0";

/* Get data from the keyboard. */
printf("\nGETS : please enter text =\n");

gets(buff);

printf("\nGETS : length is %d size is %d #%s#\n", strlen(buff),
sizeof(buff), buff);
printf("%s\n%s\ n", tmp0, tmp1);

/* Get data from the keyboard. */
printf("\nFGETS : please enter text =\n");

fgets(buff, sizeof(buff), stdin);

printf("\nFGETS : length is %d size is %d #%s#\n", strlen(buff),
sizeof(buff), buff);
printf("%s\n%s\ n", tmp0, tmp1);

printf("\nSCANF : please enter text =\n");

scanf("%s", buff);

printf("\nSCANF : length is %d size is %d #%s#\n", strlen(buff),
sizeof(buff), buff);
printf("%s\n%s\ n", tmp0, tmp1);


Dec 2 '06 #1
20 11015
Xavoux wrote:
Hello all...
I can't remind which function to use for safe inputs...
gets, fgets, scanf leads to buffer overflow...
Look at their prototypes, which one has an input size limit?

--
Ian Collins.
Dec 2 '06 #2
Xavoux wrote:
>
Hello all...
I can't remind which function to use for safe inputs...
gets, fgets, scanf leads to buffer overflow...
grade.c shows how to use fscanf for the safe input of strings
for the specific case of when it is OK to ignore
input that excedes the size of the input buffer.
The strings can then be converted to numeric data.

pops_device.c also shows how to use fscanf
for the safe input of strings
for the specific case of when it is OK to ignore
input that excedes the size of the input buffer.

line_to_string. c shows how to read strings of arbitrary
length into a linked list, using dynamic allocation.

/* BEGIN grade.c */

#include <stdlib.h>
#include <stdio.h>

#define LENGTH 3
#define str(x) # x
#define xstr(x) str(x)

int main(void)
{
int rc;
char array[LENGTH + 1];
long number;
const char letter[4] = "DCBA";

fputs("Enter the Numeric grade: ", stdout);
fflush(stdout);
rc = fscanf(stdin, "%" xstr(LENGTH) "[^\n]%*[^\n]", array);
if (!feof(stdin)) {
getc(stdin);
}
while (rc == 1) {
number = strtol(array, NULL, 10);
if (number 59) {
if (number 99) {
number = 99;
}
array[0] = letter[(number - 60) / 10];
switch (number % 10) {
case 0:
case 1:
array[1] = '-';
array[2] = '\0';
break;
case 8:
case 9:
array[1] = '+';
array[2] = '\0';
break;
default:
array[1] = '\0';
break;
}
} else {
array[0] = 'F';
array[1] = '\0';
}
printf("The Letter grade is: %s\n", array);
fputs("Enter the Numeric grade: ", stdout);
fflush(stdout);
rc = fscanf(stdin, "%" xstr(LENGTH) "[^\n]%*[^\n]", array);
if (!feof(stdin)) {
getc(stdin);
}
}
return 0;
}

/* END grade.c */

/* BEGIN pops_device.c */
/*
** If rc equals 0, then an empty line was entered
** and the array contains garbage values.
** If rc equals EOF, then the end of file was reached,
** or there is some output problem.
** If rc equals 1, then there is a string in array.
** Up to LENGTH number of characters are read
** from a line of a text stream.
** If the line is longer than LENGTH,
** then the extra characters are discarded.
*/
#include <stdio.h>

#define LENGTH 50
#define str(x) # x
#define xstr(x) str(x)

int main(void)
{
int rc;
char array[LENGTH + 1];

puts("The LENGTH macro is " xstr(LENGTH));
fputs("Enter a string with spaces:", stdout);
fflush(stdout);
rc = fscanf(stdin, "%" xstr(LENGTH) "[^\n]%*[^\n]", array);
if (!feof(stdin)) {
getc(stdin);
}
while (rc == 1) {
printf("Your string is:%s\n\n"
"Hit the Enter key to end,\nor enter "
"another string to continue:", array);
fflush(stdout);
rc = fscanf(stdin, "%" xstr(LENGTH) "[^\n]%*[^\n]", array);
if (!feof(stdin)) {
getc(stdin);
}
if (rc == 0) {
*array = '\0';
}
}
return 0;
}

/* END pops_device.c */

/* BEGIN line_to_string. c */

#include <stdio.h>
#include <stdlib.h>
#include <limits.h>
#include <string.h>
/*
** INITIAL_BUFFER_ SIZE can be any number.
** Lower numbers are more likely
** to get a non-NULL return value from malloc.
** Higher numbers are more likely to prevent
** any further allocation from being needed.
*/
#define INITIAL_BUFFER_ SIZE 0

struct list_node {
struct list_node *next;
void *data;
};

int line_to_string( FILE *fp, char **line, size_t *size);
struct list_node *string_node(st ruct list_node **head,
struct list_node *tail,
char *data);
void list_free(struc t list_node *node, void (*free_data)(vo id *));
int list_fputs(FILE *stream, struct list_node *node);

int main(void)
{
struct list_node *head, *tail;
int rc;
char *buff_ptr;
size_t buff_size;
long unsigned line_count;

buff_size = INITIAL_BUFFER_ SIZE;
buff_ptr = malloc(buff_siz e);
if (buff_ptr == NULL && buff_size != 0) {
printf("malloc( %lu) == NULL\n", (long unsigned)buff_s ize);
exit(EXIT_FAILU RE);
}
tail = head = NULL;
line_count = 0;
puts(
"\nThis program makes and prints a list of all the lines\n"
"of text entered from standard input.\n"
"Just hit the Enter key to end,\n"
"or enter any line of characters to continue."
);
while ((rc = line_to_string( stdin, &buff_ptr, &buff_size)) 1) {
++line_count;
tail = string_node(&he ad, tail, buff_ptr);
if (tail == NULL) {
break;
}
puts(
"\nJust hit the Enter key to end,\n"
"or enter any other line of characters to continue."
);
}
switch (rc) {
case EOF:
if (buff_ptr != NULL && strlen(buff_ptr ) != 0) {
puts("rc equals EOF\nThe string in buff_ptr is:");
puts(buff_ptr);
++line_count;
tail = string_node(&he ad, tail, buff_ptr);
}
break;
case 0:
puts("realloc returned a null pointer value");
if (buff_size 1) {
puts("rc equals 0\nThe string in buff_ptr is:");
puts(buff_ptr);
++line_count;
tail = string_node(&he ad, tail, buff_ptr);
}
break;
default:
/*
** If rc were to be evaluated at this point in the code,
** the value of rc
** would now be equal to (1 + strlen(buff_ptr )).
*/
break;
}
if (line_count != 0 && tail == NULL) {
puts("Node allocation failed.");
puts("The last line entered didn't make it onto the list:");
puts(buff_ptr);
}
free(buff_ptr);
puts("\nThe line buffer has been freed.\n");
printf("%lu lines of text were entered.\n", line_count);
puts("They are:\n");
list_fputs(stdo ut, head);
list_free(head, free);
puts("\nThe list has been freed.\n");
return 0;
}

int line_to_string( FILE *fp, char **line, size_t *size)
{
int rc;
void *p;
size_t count;

count = 0;
while ((rc = getc(fp)) != EOF) {
++count;
if (count + 2 *size) {
p = realloc(*line, count + 2);
if (p == NULL) {
if (*size count) {
(*line)[count] = '\0';
(*line)[count - 1] = (char)rc;
} else {
ungetc(rc, fp);
}
count = 0;
break;
}
*line = p;
*size = count + 2;
}
if (rc == '\n') {
(*line)[count - 1] = '\0';
break;
}
(*line)[count - 1] = (char)rc;
}
if (rc != EOF) {
rc = count INT_MAX ? INT_MAX : count;
} else {
if (*size count) {
(*line)[count] = '\0';
}
}
return rc;
}

struct list_node *string_node(st ruct list_node **head,
struct list_node *tail,
char *data)
{
struct list_node *node;

node = malloc(sizeof *node);
if (node != NULL) {
node -next = NULL;
node -data = malloc(strlen(d ata) + 1);
if (node -data != NULL) {
if (*head == NULL) {
*head = node;
} else {
tail -next = node;
}
strcpy(node -data, data);
} else {
free(node);
node = NULL;
}
}
return node;
}

void list_free(struc t list_node *node, void (*free_data)(vo id *))
{
struct list_node *next_node;

while (node != NULL) {
next_node = node -next;
free_data(node -data);
free(node);
node = next_node;
}
}

int list_fputs(FILE *stream, struct list_node *node)
{
while (node != NULL
&& fputs(node -data, stream) != EOF
&& putc( '\n', stream) != EOF)
{
node = node -next;
}
return node == NULL ? '\n' : EOF;
}

/* END line_to_string. c */
--
pete
Dec 2 '06 #3
thanks,

fgets dont lead to buffer overflow (my mistake)... but char not read are
leaving... and explode next read such as scanf("%d", &i);

how can i empty stdin buffer?

"Ian Collins" <ia******@hotma il.comwrote in message
news:4t******** *****@mid.indiv idual.net...
Xavoux wrote:
Hello all...
I can't remind which function to use for safe inputs...
gets, fgets, scanf leads to buffer overflow...
Look at their prototypes, which one has an input size limit?

--
Ian Collins.

Dec 2 '06 #4
"Xavoux" <xa*********@fr ee.frwrites:
I can't remind which function to use for safe inputs...
gets, fgets, scanf leads to buffer overflow...
[...]
gets(buff);
The gets() function cannot be used safely. Well, in theory, it can be
used "safely" if your program is guaranteed to run only in an
environment in which you control what will appear on stdin, but in
practice it's best to avoid it altogether.

See question 12.23 in the comp.lang.c FAQ, <http://www.c-faq.com/>.

[...]
fgets(buff, sizeof(buff), stdin);
As you can see, the fgets() function takes an argument specifying the
size of the buffer. It uses this to avoid writing past the end of the
buffer. It does have some problems of its own: it leaves the trailing
'\n', if any, in the buffer, and if the input line is too long,
fgets() reads only part of it, leaving the rest to be read later.
Both of these problems can be dealt with.

[...]
scanf("%s", buff);
This is as unsafe as gets(), but it doesn't do the same thing. gets()
and fgets() read a line at a time (from the current position to the
next '\n' character). scanf() with a "%s" format skips leading
whitespace (possibly including multiple '\n' characters), then reads a
string of contiguous non-whitespace characters. With more complex
formats, you can limit the number of characters read, avoiding buffer
overflow; see the scanf documentation (man page or whatever) for
details.

--
Keith Thompson (The_Other_Keit h) ks***@mib.org <http://www.ghoti.net/~kst>
San Diego Supercomputer Center <* <http://users.sdsc.edu/~kst>
We must do something. This is something. Therefore, we must do this.
Dec 2 '06 #5
Please don't top post.
"Ian Collins" <ia******@hotma il.comwrote:
Xavoux wrote:
Hello all...
I can't remind which function to use for safe inputs...
gets, fgets, scanf leads to buffer overflow...
Look at their prototypes, which one has an input size limit?
scanf can be used safely.

Xavoux wrote:
thanks,

fgets dont lead to buffer overflow (my mistake)... but char not read are
leaving... and explode next read such as scanf("%d", &i);
In what way?
how can i empty stdin buffer?
Why do you think you need to? [BTW, read the FAQ.]

A specific example of the problem (if you have one) is likely to be
more
useful than asking general questions. Bullet proof input in C is not as
trivial is it might seem. Different situations have different caveats.

--
Peter

Dec 2 '06 #6

"Peter Nilsson" <ai***@acay.com .auwrote in message
news:11******** **************@ l12g2000cwl.goo glegroups.com.. .
Please don't top post.
"Ian Collins" <ia******@hotma il.comwrote:
Xavoux wrote:
Hello all...
I can't remind which function to use for safe inputs...
gets, fgets, scanf leads to buffer overflow...
>
Look at their prototypes, which one has an input size limit?

scanf can be used safely.

Xavoux wrote:
thanks,

fgets dont lead to buffer overflow (my mistake)... but char not read are
leaving... and explode next read such as scanf("%d", &i);

In what way?
how can i empty stdin buffer?

Why do you think you need to? [BTW, read the FAQ.]

A specific example of the problem (if you have one) is likely to be
more
useful than asking general questions. Bullet proof input in C is not as
trivial is it might seem. Different situations have different caveats.

--
Peter
i want to manage input of, at most k values (double)
user need to be able to give less than k in a time

k is variable
Dec 2 '06 #7

"Xavoux" <xa*********@fr ee.frwrote in message
news:45******** *************** @news.orange.fr ...
Hello all...
I can't remind which function to use for safe inputs...
gets, fgets, scanf leads to buffer overflow...

i compiled that code with gcc version 2.95.2, on windows 2000

char tmp0[10] = "ABCDEFGHI\ 0";
char buff[5]; /* Input buffer. */
char tmp1[10] = "ABCDEFGHI\ 0";

/* Get data from the keyboard. */
printf("\nGETS : please enter text =\n");

gets(buff);

printf("\nGETS : length is %d size is %d #%s#\n", strlen(buff),
sizeof(buff), buff);
printf("%s\n%s\ n", tmp0, tmp1);

/* Get data from the keyboard. */
printf("\nFGETS : please enter text =\n");

fgets(buff, sizeof(buff), stdin);

printf("\nFGETS : length is %d size is %d #%s#\n", strlen(buff),
sizeof(buff), buff);
printf("%s\n%s\ n", tmp0, tmp1);

printf("\nSCANF : please enter text =\n");

scanf("%s", buff);

printf("\nSCANF : length is %d size is %d #%s#\n", strlen(buff),
sizeof(buff), buff);
printf("%s\n%s\ n", tmp0, tmp1);

gets() doesn't take the buffer size as an argument, so it is impossible to
prevent a long line from overflowing the buffer.
fgets() does. However there is very little point in simply truncating the
line and treating it as valid input - that is extremely likely to lead to a
serious bug as a number is half-read or something similar.

If you know how long valid lines can be, write

char buff[MAXLINELEN + 1];

fgets(buff, sizeof buff, fp);
if(!strchr(buff , '\n'))
{
fprintf(stderr, "line too long\n");
exit(EXIT_FAILU RE);
}

if you don't, fgets() is virtually useless. Use a function that read
arbitrarily long lines instead. Chuck falconer has one avialable called
ggets().
--
www.personal.leeds.ac.uk/~bgy1mm
freeware games to download.
Dec 2 '06 #8
On Sat, 02 Dec 2006 14:15:24 +1300, Ian Collins <ia******@hotma il.com>
wrote:
>Xavoux wrote:
>Hello all...
I can't remind which function to use for safe inputs...
gets, fgets, scanf leads to buffer overflow...
Look at their prototypes, which one has an input size limit?
The function gets() does not have an input size. But that didn't stop
the authors of the C standard from defining gets() to return a
pointer. If the return value is NULL, a read error occurred, and the
array contents are indeterminate. This implies that you must always
check the return value of gets(), if you want to avoid accessing an
array contents that is indeterminate.

You can and should avoid the pitfalls of gets() (accessing an array
contents that is indeterminate, and undefined behavior), by not using
gets().

--
jay
Dec 2 '06 #9
Xavoux wrote:
"Peter Nilsson" <ai***@acay.com .auwrote in message
[snip]
A specific example of the problem (if you have one) is likely to be
more
useful than asking general questions. Bullet proof input in C is not as
trivial is it might seem. Different situations have different caveats.
[snip]
i want to manage input of, at most k values (double)
user need to be able to give less than k in a time

k is variable
Download the following:
<http://cbfalconer.home .att.net/download/ggets.zip>

Use it to read in lines of arbitrary size. Then use strtod() to attempt
to convert each line to a double. This is a quite robust solution.

You won't need to worry about discarding unread input from stdin if you
use the above method.

Dec 2 '06 #10

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

39
100804
by: Teh Charleh | last post by:
OK I have 2 similar programmes, why does the first one work and the second does not? Basically the problem is that the program seems to ignore the gets call if it comes after a scanf call. Please anything even a hint would be really helpful, I cant for the life of me see why the 2nd prog wont work... gets before scanf code:---------------------------------------------------------------------
57
11770
by: Eric Boutin | last post by:
Hi ! I was wondering how to quickly and safely use a safe scanf( ) or gets function... I mean.. if I do : char a; scanf("%s", a); and the user input a 257 char string.. that creates a problem.. same for gets.. even if you create a char array that's 99999999999999 char long.. if the user input something longer it will still be a bug.. and I don't want
10
3736
by: Stuart Anderson | last post by:
I am looking to use Ken Stephenson's CirclePack program (http://www.math.utk.edu/~kens/) with some tiling programs written by Cannon, Floyd, Parry. The programs I want to use are subdivide.c tilepack.c squarect.c . They are available from http://www.math.vt.edu/people/floyd/research/software/subdiv.html. I tried compiling them on my Redhat 9 box, eg cc subdivide.c. When I do so I get errors like "In function `Readtilingforvertex': :...
45
3445
by: Anthony Irwin | last post by:
Hi, I am fairly new to C and all the C books I got talk about gets() but when I compile it says I should not use gets() because it is dangerous. I understand that it is dangerous because it doesn't check whether there is more characters entered by the user the what can be stored but I don't know what the safe equivalent of gets() is. Below is an example program I have written. (GCC is my compiler on GNU/Linux system.)
280
8976
by: jacob navia | last post by:
In the discussion group comp.std.c Mr Gwyn wrote: < quote > .... gets has been declared an obsolescent feature and deprecated, as a direct result of my submitting a DR about it (which originally suggested a less drastic change). (The official impact awaits wrapping up the latest batch of TCs into a formal amending document, and getting it approved and published.)
0
8786
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
9467
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
1
9257
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
8203
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
6749
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
4567
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
4823
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
3278
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
3
2192
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.