求助,段错误怎么办
#include "std.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int len = 0;
struct node
{
char *word;
int count;
struct node *next;
}*head,*p,*q;
struct node* printf_sort(struct node *head)
{
struct node *p1,*p2,*ptemp,*pfinished = NULL;
for (p1 = head; p1->next != pfinished;)
{
for (p2 = p1; p2->next != pfinished;)
{
if (p2->count < p2->next->count)
{
if (p2 == p1)
{
p1 = p2->next;
p2->next = p1->next;
p1->next = p2;
ptemp = p1;
}
else
{
ptemp->next = p2->next;
ptemp = p2->next;
p2->next = ptemp->next;
ptemp->next = p2;
}
}
else
{
ptemp = p2;
p2=p2->next;
}
}
pfinished = p2;
}
}
int main(int argc, char *argv[])
{
int ndisp = 0;
struct timeval starttime, endtime, durtime;
int i = 0;
/* step0: get cmd parameter and check it */
if (argc < 2){
printf("USAGE: wordcount <filename> [Top # of results to display]\n");
exit(0);
}
char *filename = *(argv + 1);
/* step1: prepare work (e.g. open file, load file to memory ...) */
FILE *file;
if ((file = fopen(filename, "r")) == NULL){
printf("cannot open this file\n");
exit(0);
}
printf("wordcount: Running...\n");
gettimeofday(&starttime, 0);
/* step2: do word count */
char ch;
head = NULL;
while ((ch = fgetc(file)) != EOF)
{
while (ch == ' ')
ch = fgetc(file);
if (ch <= 'Z')
ch += 32;
i = 0;
q = (struct node *) malloc(sizeof(struct node));
char temp[20];
while (ch = fgetc(file) != ' ')
{
temp[i] = ch;
i++;
}
int same = 0;
for (p = head; p != NULL; p = p->next)
{
if (strcmp(temp, p->word) == 0)
{
p->count++;
same = 1;
}
}
if (same == 0)
{
strcpy(q->word, temp);
p->next = q;
}
}
gettimeofday(&endtime, 0);
GET_TIME(starttime, endtime, durtime);
printf("wordcount: completed %ld.%ld(s)\n", durtime.tv_sec, durtime.tv_usec);
printf("wordsort: running ...\n");
gettimeofday(&starttime, 0);
/* step3: sort the results */
printf_sort(head);
gettimeofday(&endtime, 0);
GET_TIME(starttime, endtime, durtime);
printf("wordsort: completed %ld.%ld(s)\n", durtime.tv_sec, durtime.tv_usec);
/* step4: print results */
ndisp = head->count;
printf("\nwordcount: results (TOP %d from %d):\n", ndisp, len);
p = head;
if (head != NULL)
{
do
{
printf("%s - %d\n", p->word, p->count);
p = p->next;
}while (p != NULL);
}
/* step5: destroy work (e.g. free memory, close file ...) */
fclose(file);
free(head);
return 0;
}如上。程序目的是读入文件的单词并统计每一个单词的数目,然后按照数目降序打印出来。
编译可以通过,运行发生段错误,调试发现如下错误:
0x00007ffff7b664e2 in ?? () from /lib/x86_64-linux-gnu/libc.so.6
希望各位帮忙解决一下
...全文
相关推荐
段错误解决方法
段错误的原因**- **无效指针**:程序可能尝试通过一个空指针或未初始化的指针访问内存,导致段错误。- **越界数组访问**:当程序试图访问数组的边界之外的内存时,可能会触发段错误。
Linux下的段错误产生的原因及调试方法
### Linux下的段错误产生的原因及调试方法在深入探讨Linux下段错误的产生原因与调试方法之前,我们先来理解一下“段错误”(Segmentation Fault)的基本概念。
C语言段错误 总结 段错误整理
C语言段错误总结C语言中的段错误是指访问了不可访问的内存,这个内存区要么是不存在的,要么是受到系统保护的。段错误是一个非常麻烦的问题,因为它可能导致程序崩溃或出现不可预料的结果。一、什么是段错误?
段错误的调试
### 段错误的调试详解#### 一、段错误概念与原理段错误(Segmentation Fault)是一种常见的编程错误,通常发生在程序试图访问非法内存地址时。
段错误(linux)
#### 段错误的原因及实例段错误的发生有多种可能的原因,以下是一些常见的原因及其示例:1.


