2014-10-29 72 views
1

以下代码片段正在扫描包含单词'Int'或'Float'的有效句子的命令行参数。C:字符串,分段错误

我已经调试了几个小时试图找到错误发生的地方无济于事。

任何帮助,将不胜感激。

#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; 
} 
+1

你需要之前,你'的strcpy(文字,argv的[1])为'word'分配内存'...或者你可以避开副本,如果你不打算修改的字。 – SleuthEye 2014-10-29 04:07:01

+0

如果您使用的是UNIX的风格,您可以使用GDB。 – 2014-10-29 04:14:13

+0

如果我不修改这个词,我应该用什么来复制字符串? – 2014-10-29 04:17:00

回答

3

在使用之前,您没有为word分配内存。尝试像

 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; 
     } 
+0

不要忘记一旦完成释放内存 – P0W 2014-10-29 04:12:11

+0

@PW of course我不会忘记。只是为了给我写一个想法。 – 2014-10-29 04:13:07

+0

这是为OP,没关系,它总是一个很好的做法,写回答,如果OP不知道它,他(他)可能最终会泄漏资源 – P0W 2014-10-29 04:15:29