gpt4 book ai didi

c - 一个简单的 C 链表程序可能存在内存问题

转载 作者:太空宇宙 更新时间:2023-11-04 08:37:35 25 4
gpt4 key购买 nike

我正在尝试编写一个程序来计算段落中单词的出现次数。

我遵循的逻辑:我正在为此目的使用链表。我正在按顺序搜索 - 如果遇到新词,则在列表中添加该词,但如果该词已存在于列表中,则增加其计数标志。

//case insensitive string matching
int strcicmp(char const *a, char const *b)
{
int d;
for(;;a++,b++)
{
d=tolower(*a)-tolower(*b);
if(d!=0 || !*a)
return d;
}
}

//declare the linked list structure to store distinct words and their count
typedef struct node
{
char *word;
int count;
struct node *next;
} node;

node *ptr, *newnode, *first=NULL, *last=NULL;

void insertnewword(char *ch)
{
newnode=(node*)malloc(sizeof(node));
if(newnode == NULL)
{
printf("\nMemory is not allocated\n");
exit(0);
}
else
{
newnode->word=ch;
newnode->count=1;
newnode->next=NULL;
}

if(first==last && last==NULL)
{
first=last=newnode;
first->next=NULL;
last->next=NULL;
}
else
{
last->next=newnode;
last=newnode;
last->next=NULL;
}
}

void processword(char *ch)
{
int found=0;
//if word is already in the list, increase the count
for(ptr=first;ptr!=NULL;ptr=ptr->next)
if(strcicmp(ptr->word, ch) == 0)
{
ptr->count += 1;
found=1;
break;
}

//if it's a new word, add the word to the list
if(!found)
insertnewword(ch);
}

int main()
{
const char *delimiters=" ~`!@#$%^&*()_-+={[}]:;<,>.?/|\\\'\"\t\n\r";
char *ch, *str;
str=(char*)malloc(sizeof(char));
ch=(char*)malloc(sizeof(char));

//get the original string
scanf("%[^\n]%*c", str);
//fgets(str, 500, stdin);

//get the tokenized string
ch=strtok(str,delimiters);
while(ch!=NULL)
{
//a, an, the should not be counted
if(strcicmp("a", ch)!=0 && strcicmp("an", ch)!=0 && strcicmp("the", ch)!=0)
processword(ch);

ch=strtok(NULL,delimiters);
}

//print the word and it's occurrence count
for(ptr=first; ptr!=NULL; ptr=ptr->next)
printf("%s\t\t%d\n",ptr->word,ptr->count);
return 0;
}

这似乎适用于少量单词,但如果单词数超过 6-7,则该程序会遇到一些问题。

说输入是:我是个好 child 。我是个坏男孩。

输入应该是

我 2上午 2好 1坏 1男孩 2

但我得到的是我 2上午 2好 1坏 1(一些垃圾字符)1

我总是可以为同一个问题实现任何其他逻辑,但我想知道这个实现的问题。

提前致谢

最佳答案

我认为问题出在您的 scanf 上:

在 man scanf 中:
下一个指针必须是指向 char 的指针,并且必须有足够的空间容纳字符串中的所有字符,外加一个终止空字节

但是在你的 main 的顶部,你的 char 数组的分配只有一口长:str=(char*)malloc(sizeof(char));

我觉得还是用getline之类的函数比较好

ssize_t getline(char **lineptr, size_t *n, FILE *stream);并设置 lineptr 指向 NULL

关于c - 一个简单的 C 链表程序可能存在内存问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25620970/

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