gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 17:07:26 25 4
gpt4 key购买 nike

我编写了一个程序,它接受 1 个或多个文本文件,并以 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 );

关于c - 为什么这个程序会出现段错误错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34074183/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com