2015-12-03 248 views
0

我做了一個程序,它接受一個或多個文本文件,並以ASCII順序打印單詞內的出現次數,一個單詞可以是字母數字的任意組合。我使用了一個鏈表,並且出現了分段錯誤錯誤。這個程序爲什麼會出現分段錯誤錯誤

#include <stdio.h> 
#include <stdlib.h> 
#include <malloc.h> 
#include <ctype.h> 
#include <string.h> 

struct words{ 
    char *word; 
    int count; 
    struct words *next; 
}; 

struct words *head = NULL; 

struct words *createnode(char *n) 
{ 
    struct words *p; 

    if ((p = (struct words *) malloc(sizeof(struct words))) == NULL) 
     return(NULL); 

    strcpy(p->word, n); 
    p->next = NULL; 

    return(p); 
} 

struct words *insert(struct words *new) 
{ 
    struct words *prev, *temp; 
    int compare;  

    if (head == NULL) 
     return(new); 

    compare = strcmp(head->word,new->word); 

    if(compare > 0){ 
     new->next = head; 
     return(new); 
    } 

    if(compare == 0){ 
     head->count++; 
     return(head); 
    } 

    prev = head; 
    temp = head->next; 
    if(compare < 0){ 
     while(temp != NULL && strcmp(temp->word,new->word) < 0){ 
      prev = temp; 
      temp = temp->next; 
     } 
    } 
    new->next = temp; 
    prev->next = new; 

    return(head); 
} 

char *whiteSpace(char *buf){ 
    int i; 
    for(i = 0; buf[i] != '\0'; i++) 
    { 
     if(!isalnum(buf[i])) 
     { 
      buf[i] = ' '; 
     } 
    } 

return(buf); 

} 

int main(int argc, char *argv[]){ 

    FILE *fp; 
    char buf[100]; 
    int lineNum = 1; 
    char *token; 
    struct words *p; 
    const char s[2] = " "; 
    int i; 
    printf("test"); 
    for(i=1;i<argc;i++){ 

     fp = fopen(argv[i], "r"); 
     if(fp == NULL){ 
      perror(argv[i]); 
     } 

     while(fgets(buf, 99, fp) != NULL){ 
      whiteSpace(buf); 
      token=strtok(buf, s); 
      while(token != NULL){ 
       if((p=createnode(token)) == NULL){ 
        fprintf(stderr, "%s, file %s, line %d: ran out of memory \n", token, argv[argc], lineNum); 
        return(1); 
       } 
       else{ 
        head = insert(p); 
       } 
       token = strtok(NULL, buf); 
       } 
     lineNum = lineNum+1;  
     } 
     for(p = head; p!= NULL; p = p->next){ 
      printf("%5d %s\n", p->count, p->word); 

     } 

    } 
    return(0); 

} 
+1

您可以打開調試和點代碼中你看到了嗎? – Phani

回答

0

問題,我看到

createnode,你還沒有使用

strcpy(p->word, n); 

添加一行調用strcpy之前p->word分配內存之前p->word分配的內存。

p->word = malloc(strlen(n)+1); 
strcpy(p->word, n); 

您還可以在main調用strtok錯誤。您正在使用

token = strtok(NULL, buf); 

這應該是

token = strtok(NULL, s); 
+0

謝謝,它修復了分段錯誤。但是,現在我認爲我的計劃總體上存在缺陷。如果我輸入一個包含「hello hello hello」的文本文件,我會得到這個「0 0 hello」,任何提示? – janw

+0

@janw,查看更新後的答案 –

相關問題