2014-10-29 77 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