c - using an array member in a data structure -
i have following data structure:
typedef struct node { int key; int *v; }node; ... , global variables:
node *multiway[10]; int contor=0; i trying insert inside structure nodes of multiway tree, , kids of each node. in order this, made function:
int * getkids(int value,int n) //returneaza vectorul de copii ai unui nod { //value-nodul parinte //n- numarul de noduri ale vectorului int *result=(int*)malloc(n*sizeof(int)); int counter=0; int i; for(i=1;i<=n;i++) { if(a[i]==value) { counter++; result[counter]=i; printf("%d ",result[counter]); } } int copii[counter]; //in vector pun toti copiii valorii date, value for(i=1;i<=counter;i++) { copii[i]=result[i]; } contor++; multiway[contor]=(node*)malloc(sizeof(node)); //added line after comment multiway[contor]->key=value; //segmentation fault multiway[contor]->v=copii; return result; } my code compiles no warnings, when run, crashes. when debug, segmentation fault @ line commented "segmentation fault". idea of did wrong? thank you.
many issue code. point out of them
array indexing
for(i=1;i<=n;i++) { if(a[i]==value)
arrays in c has 0 based index. so, should for(i=0;i< n;i++). did not show a is.
in case of
int copii[counter];
what if if(a[i]==value) never becomes true?
in case of
multiway[contor]->key=value; //segmentation fault multiway[contor]->v=copii;
what if contor more 9? you'll overrunning memory.
a function local variable's lifetime till function finishes execution. once function finished, variable won't present anymore. trying access variable produces undefined behavior.
multiway[contor]->v=copii;
in above case, copii local getkids(), , after getkids() finishes execution, trying access multiway[contor]->v lead ub.
note: do not cast return value of malloc() , family.
Comments
Post a Comment