kschmid
kschmid

Reputation: 33

Value of struct member changes after printing C

I got this code and a strange behaviour while printing the id member variable of node.

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

struct node
{
    int id;
    int visited;
//    struct node *neighbors_[];
};

struct graph
{
    struct node nodes[26];
    int adjMat[26][26];

};

struct stack_item
{
    struct node node;
    struct stack_item *next_;
};

struct myStack
{
    struct stack_item *anfang_;

};

void initGraph(struct graph *graph_);
void push(struct myStack *stack_, struct node node);

int main()
{

    struct graph graph;
    struct myStack stack;
    char ausgabe[26]="";

    initGraph(&graph);


    //READ DATA
    char line[200];
    int firstTime=1,first;

    first=0;
    push(&stack,graph.nodes[first]);

    printf("ID %i\n",stack.anfang_->node.id);
    printf("ID %i\n",stack.anfang_->node.id);

    //FINISHED DATA READING
     //CALL DFS
    //dfs(graph,stack,ausgabe);
}

void push(struct myStack *stack_, struct node node)
{
    struct stack_item item;
    item.node=node;
    item.next_=stack_->anfang_;

    stack_->anfang_=&item;
}

void initGraph(struct graph *graph_)
{
    int i,j;
    for(i=0; i<26; i++)
    {
        struct node node= {i,0};
        graph_->nodes[i]=node;

        for(j=0; j<26; j++)
        {

            graph_->adjMat[i][j]=0;

        }
    }
}

If i execute this, the first print command leads to 'ID 0',the second to 'ID 1980796117'. How can this value change by printing it? Could please anyone help me, i've got really no idea!

Upvotes: 3

Views: 232

Answers (1)

Ed Swangren
Ed Swangren

Reputation: 124642

void push(struct myStack *stack_, struct node node)
{
    struct stack_item item;
    item.node=node;
    item.next_=stack_->anfang_;

    /* BAD! */
    stack_->anfang_=&item;
}

item is a local variable which, when the push function returns, goes out of scope. Any existing pointers which refer to this object are now invalid, and dereferencing it results in undefined behavior.

You will need to dynamically allocate item (i.e., malloc) if you need it to persist once the function has returned.

Upvotes: 5

Related Questions