C++ Why pointer value changed? -


i testing linked link. however, list address passed function getelement() not expected after insert element list , list should reference type. can't understand why.

this main program:

#include "stdafx.h" #include <string> #include <iostream>  typedef struct node {     int data;     struct node *next; } node;  typedef struct node *linklist;  void insertelement(linklist *header, int i, int e) {     linklist p = *header;     int j = 0;      while (p && j < i)     {         p = p->next;         j++;     }      if (!p || j > i)         return;      node newnode;     newnode.data = e;     newnode.next = p->next;      p->next = &newnode; }  void getelement(linklist list, int i, int *value) {     linklist p = list->next;     int j = 1;     while (p && j < i)     {         p = p->next;         j++;     }     if (!p || j >= i)         return;      *value = p->data; } int _tmain(int argc, _tchar* argv[]) {     linklist header = (linklist)malloc(sizeof(node));     header->next = null;      insertelement(&header, 0, 1);     int res = -1;     getelement(header, 1, &res);  } 

when debugging, found parameter "list" in function getelement() changed once enters function.

here problem:

node newnode; ... p->next = &newnode; // <<== using pointer local 

newnode above local variable goes out of scope, along memory, function exits. causes undefined behavior, because memory node deallocated.

using malloc instead, way did in _tmain, fix problem. better yet, use new, since c++, , malloc c-style allocation.

once fix issue, issue related number of nodes pop up: allocating node assigned head, left unused. since passing pointer pointer anyway, should pass pointer header, , modify through double-pointer.


Comments

Popular posts from this blog

cakephp - simple blog with croogo -

How to group boxplot outliers in gnuplot -

bash - Performing variable substitution in a string -