Reputation: 11
The following piece of code is scanning for command line arguments for valid sentences that contains the words 'Int' or 'Float'.
I have debugged it for hours trying to locate where the error is occurring to no avail.
Any help would be appreciated.
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include <ctype.h>
#include <string.h>
bool process_input(int, char *[]);
bool first_word_correct(char *);
void print_string(char *);
int main(int argc, char *argv[]) {
if (!process_input(argc, argv))
printf("Incorrect input.\n");
else
printf("CORRECT input.\n");
return EXIT_SUCCESS;
}
bool process_input(int argc, char *argv[]) {
char *word;
int i, j;
bool is_new_sentence = true;
i = 0;
j = 0;
while (++i < argc) {
// check the first word - must be "A" or "An"
if (is_new_sentence) {
if (!first_word_correct(argv[i])) {
return false;
}
is_new_sentence = false;
}
// we're checking subsequent words of the same sentence
else if (!is_new_sentence) {
// is this the last word?
strcpy(word, argv[i]);
if (word[strlen(word) - 1] == '.') {
is_new_sentence = true;
}
switch(is_variable_name(word)) {
case 1:
printf("int found!\n");
break;
case 2:
printf("float found!\n");
break;
}
}
}
return true;
}
bool first_word_correct(char *word) {
if (strcmp(word, "A") == 0 || strcmp(word, "An") == 0) {
return true;
}
else {
return false;
}
}
/*
*int 1
*float 2
*/
int is_variable_name(char *word) {
if ((strcmp(word, "int") == 0) || (strcmp(word, "int.") == 0))
return 1;
if ((strcmp(word, "float") == 0) || (strcmp(word, "float.") == 0))
return 2;
return -1;
}
Upvotes: 1
Views: 69
Reputation: 1346
You are not allocated memory for word
before using it. Try like
else if (!is_new_sentence) {
// is this the last word?
word=malloc(100);// size is based on your argv[i]
strcpy(word, argv[i]);
if (word[strlen(word) - 1] == '.') {
is_new_sentence = true;
}
Upvotes: 3