为什么这个程序会出现分段错误错误

时间:2015-12-03 19:08:37

标签: c

我创建了一个程序,它接受一个或多个文本文件并以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 个答案:

答案 0 :(得分:0)

我看到的问题

createnode中,您在使用

之前尚未为p->word分配内存
strcpy(p->word, n);

在调用p->word之前,添加一行以为strcpy分配内存。

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

strtokmain的调用也出错。您正在使用

token = strtok( NULL, buf );

那应该是

token = strtok( NULL, s );