Peter
Peter

Reputation: 449

Why does my program sometimes returns 0xc0000005 and sometimes runs well?

can you tell me why this program sometimes returns 0xc0000005 (crash) and sometimes it runs well? I am beginner in C and have no idea what is wrong. I am using GNU GCC compiler and Code::Blocks. Thank you in advance.

#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;
}

Upvotes: 0

Views: 662

Answers (2)

user3386109
user3386109

Reputation: 34839

You've created a typedef for a pointer

typedef MEMBER *LINKED_LIST;

Then you've declared a couple of pointers using that typedef

LINKED_LIST curr, head;

When you allocate space for curr you probably intended to allocate space for a copy of the structure, but instead you allocated space for a pointer.

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

So the following line results in undefined behavior because you haven't actually allocated space for the structure.

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

Moral of the story: don't create typedef's for pointers.
Side note: also don't cast the return value of malloc.

Upvotes: 5

Some programmer dude
Some programmer dude

Reputation: 409403

This line is very suspicious:

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

What if curr is the last node in the list? Then you dereference a NULL pointer.

Upvotes: 2

Related Questions