Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I'm relatively new to C and I was creating a program that involves a linked-list. Here is a very abbreviated version of the code that's giving me trouble.

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

#define STRLEN 100

struct Gene { 
    int num[4];
    struct Gene *next;
    };
typedef struct Gene item;

void build_list(item *current, item *head, FILE *in);

int main() {

    FILE *input;
    FILE *output;
    input = fopen("test.data", "r");
    output = fopen("test.out", "w+");

    item *curr;
    item *head; 
    head = NULL;
    int i;

    build_list(curr, head, input);
    curr = head;

    while(curr) {
        for (i = 0; i < 4; ++i)
            fprintf(output, "%d
", curr->num[i]);
        curr = curr->next;
        }

    fclose(input);
    fclose(output);
    free(curr);
}

void build_list(item *current, item *head, FILE *in) {

    char gene[STRLEN];
    char *tok;
    char gene_name[STRLEN];
    char *search = ",";
    int j;

    while (fgets(gene, sizeof(gene), in)) {

        current = (item *)malloc(sizeof(item));
        tok = strtok(gene, search);
        strcpy(gene_name, tok);
        for (j = 0; j < 4; ++j) {
            tok = strtok(NULL, search);
            current->num[j] = atoi(tok);
            }
        current->next = head;
        head = current;
    }
}

When I try to compile this, it says variable curr is uninitialized, but even when I initialize it with malloc it throws a segmentation fault, or it prints out nothing at all. Why could this be?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
283 views
Welcome To Ask or Share your Answers For Others

1 Answer

C uses pass by value for function argument passing. So, when you call build_list(curr, head, input);, curr and head themselves are passed by value and any changes made to those variables (corresponding parameters) will not reflect back to the caller.

So, in the caller,

 while(curr)

is accessing unitialized variable (meeory) which invokes undefined behavior.

If you need to change curr and head themselves, you need to pass their address and make chages inside the funtion. Something like

 build_list(&curr, &head, input);

and

void build_list(item **current, item **head, FILE *in)

and

*current = malloc(sizeof(item));

may get the job done for you.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...