How to fix a string overflow?
Good afternoon. I started a new program called expand which expands a-e to
abcde (KnR exercise) however I've been doing this since I began to code:
Code:
#ifndef MAXSIZE
#endif MAXSIZE 1000
#endif
or similar to control the size of the string. But I know a person can overflow it with 1001 chars. So, what's the definitive way to fix this problem?
the program I'm starting to code :
edit:
Why can't I oblige the input of two letters and an hyphen with that do-while ?
Code:
#include <stdio.h>
#include <string.h>
#include <ctype.h>
#include <stdlib.h>
#ifndef ALPHA
#define ALPHA 26
#endif
#ifndef MAXSIZE
#define MAXSIZE 1000
#endif
void justLetters(char*);
void expand(char*, char*);
void justLetters(char* s)
{
int i, j;
for(i = 0, j = 0; i < strlen(s); i++)
{
if(isalpha( (unsigned char) s[i]) )
s[j++] = s[i];
}
s[j] = '\0';
}
void expand(char* s, char* result)
{
int i;
char alphabet[ALPHA] = "abcdefghijklmnopqrstuvwxyz";
justLetters(s);
printf("The string is %s\n", s);
}
int main(void)
{
char *s = malloc(MAXSIZE * sizeof(char));
char *result = malloc(MAXSIZE * sizeof(char));
do {
printf("Enter two letters separated by hyphens: ");
if(fgets(s, MAXSIZE, stdin))
printf("You entered: %s", s);
} while((!isalpha( (unsigned char) s[0]) ) && (s[1] != '-') &&
(!isalpha( (unsigned char) s[2]) ) );
expand(s, result);
free(s);
free(result);
return 0;
}