为什么我的程序有时返回0xc0000005并且有时运行良好?

时间:2014-12-31 00:25:59

标签: c crash

你能告诉我为什么这个程序有时会返回0xc0000005(崩溃),有时运行良好吗?我是C的初学者,不知道出了什么问题。我正在使用GNU GCC编译器和Code :: Blocks。提前谢谢。

#include<stdlib.h>
#include<stdio.h>
#include<string.h>
#include<ctype.h>

typedef struct member {
int number;
char *line;
struct member *next;
}MEMBER;

typedef MEMBER *LINKED_LIST;

int main() {
char file_line [120], *str;
FILE *fi, *fo;
LINKED_LIST curr, head;
int count = 0, count_sort = 0 , end_sort, tmpint;

fi = fopen("vstup.txt","r");
if(fi == NULL){
    printf("vstup.txt - ERROR when opening file/file not found\n");
    return 0;
}
curr = (LINKED_LIST)malloc(sizeof(LINKED_LIST));
head = curr;
while(fgets(file_line,sizeof(file_line),fi))
{
    curr->number = strtol(file_line, &str,10);
    while(isspace(*str))
        str++;
    curr->line = strdup(str);
    curr->next = (LINKED_LIST)malloc(sizeof(LINKED_LIST));
    curr = curr->next;
    memset(&file_line,0,120);
    count++;
}
curr->next = NULL;
curr = NULL;
curr = head;
count_sort = count-1;
end_sort = count;
while(end_sort)
{
    if((curr->number) > (curr->next->number))
    {
        tmpint = curr->number;
        curr->number = curr->next->number;
        curr->next->number = tmpint;

        str = curr->line;
        curr->line = curr->next->line;
        curr->next->line = str;
    }
    curr = curr->next;
    count_sort--;
    if(count_sort == 0)
    {
        count_sort = count-1;
        curr = head;
        end_sort--;
    }
}
curr = head;
fclose(fi);
if (count == 0)
{
    printf("List/file is empty.\n\n");
    return 0;
}
fo = fopen("vystup.txt","w");
while(count)
{
    fprintf(fo,"%s", curr->line);
    curr = curr->next;
    count--;
}
printf("Success!\n");
fclose(fo);
return 0;
}

2 个答案:

答案 0 :(得分:5)

您已为指针

创建了typedef
typedef MEMBER *LINKED_LIST;

然后,您已使用该typedef

声明了几个指针
LINKED_LIST curr, head;

curr分配空间时,您可能打算为结构的副本分配空间,而是为指针分配空间。

curr = (LINKED_LIST)malloc(sizeof(LINKED_LIST));

因此,以下行导致未定义的行为,因为您实际上没有为结构分配空间。

    curr->number = strtol(file_line, &str,10);

故事的道德:不要为指针创建typedef 附注:也不要投放malloc的返回值。

答案 1 :(得分:2)

此行非常可疑:

if((curr->number) > (curr->next->number))

如果curr是列表中的最后一个节点怎么办?然后你取消引用NULL指针。