簡體   English   中英

為什么該程序出現分段錯誤錯誤

[英]Why is this program getting segmentation fault error

我制作了一個程序,該程序可以接受一個或多個文本文件,並以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);

}

我看到的問題

createnode ,您沒有在使用前為p->word分配內存

strcpy(p->word, n);

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

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

您對main strtok的調用中也有一個錯誤。 您正在使用

token = strtok( NULL, buf );

那應該是

token = strtok( NULL, s );

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM