[TriLUG] a C question (overkill)
P. L. Charles Fischer
fischer at pop3.zedec.com
Wed Oct 23 10:58:16 EDT 2002
Here is the overkill version of your program. It checks for buffer overflow
and shows two way to get the text into the program.
#include <stdio.h> /* needed for file input and output */
#include <stdlib.h> /* needed for malloc and free if you use them */
#define STR_LENGTH 256 /* define the maximum string input length */
#define ALLOC_MEM 1 /* comment this line out if you want to avoid malloc */
int main(int argc, char *argv[]) /* do not worry about argc and argv at
this time */
{
#ifdef ALLOC_MEM /* only one text variable will be used */
char *text; /* Folks will argue which way is better */
/* this way leaves the stack small, which is */
/* good for debuging. Stack overflows can be */
/* hard to find. */
#else
char text[STR_LENGTH]; /* in this small of a progam it does not matter */
/* if you use the stack, but you may get into */
/* bad habits. */
#endif
int fav_num; /* integer variable for your input integer */
char *ret_str; /* string returned from fgets function */
int ret_int; /* number of fields converted from sscanf */
#ifdef ALLOC_MEM
text = malloc(STR_LENGTH); /* get the memory for the text input variable */
if (text == NULL) /* check to make sure you got your memory */
{
fprintf(stderr, "Could not get the memory for some odd reason.\n");
exit(-1);
}
#endif
printf("What is your favorite number?\n"); /* prompt the user to enter a
number */
ret_str = fgets(text, STR_LENGTH, stdin); /* get the input string, limit
the input to STR_LENGTH */
/* characters this will solve buffer overflow problems */
if (ret_str == NULL) /* check for nothing entered */
{
fprintf(stderr, "Could not read input string for some odd reason\n");
exit(-2);
}
ret_int = sscanf(text, "%d", &fav_num); /* take the input string and read
the first field as an integer */
if (ret_int != 1)
{
fprintf(stderr, "You did not input a integer as the first part of the
input string.\n");
exit(-3);
}
printf("\n\nYour favorite number is %d\n\n", fav_num);
#ifdef ALLOC_MEM /* free memory from text input for other use */
free(text); /* some say you should do this, but when the */
/* program ends the OS will do it for you */
#endif
return(0);
}
____________________________________________________________________________
P. L. Charles Fischer fischer at zedec.com
VOX: 919.465.2306 800.894.0058
ZEDEC Technologies FAX: 919.465.2309
____________________________________________________________________________
More information about the TriLUG
mailing list