Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
292 views
in Technique[技术] by (71.8m points)

function - C: Variable is uninitialized for linked list

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

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

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...