-2

I have the following data structure:

typedef struct node
{
    int key;
    int *v;
}node;

... and the global variables:

node *multiway[10];
int contor=0;

I am trying to insert inside this structure all the nodes of a multiway tree, and all the kids of each node. In order to do this, I made this 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 this line after a comment
    multiway[contor]->key=value; //SEGMENTATION FAULT
    multiway[contor]->v=copii;
    return result;
}

My code compiles with no warnings, but when I run, it crashes. When I debug, I get a segmentation fault at the line which I commented with "Segmentation fault". Any idea of what I did wrong? Thank you.

Sportler
  • 9
  • 5

1 Answers1

0

Many issue with your code. To point out some of them

  1. Array indexing

    for(i=1;i<=n;i++)
    {
        if(a[i]==value)
    

arrays in c has 0 based index. So, basically it should be for(i=0;i< n;i++). You also did not show us what a is.

  1. In case of

    int copii[counter];
    

what if if(a[i]==value) never becomes TRUE?

  1. In case of

    multiway[contor]->key=value; //SEGMENTATION FAULT
    multiway[contor]->v=copii;
    

what if contor is more than 9? You'll be overrunning the memory.

  1. a function local variable's lifetime is till the function finishes execution. Once the function is finished, that variable won't be present anymore. Trying to access that variable produces undefined behavior.

    multiway[contor]->v=copii;
    

in the above case, copii is local to getKids(), and after getKids() finishes execution, trying to access multiway[contor]->v will lead to UB.

Note: Do not cast the return value of malloc() and family.

Community
  • 1
  • 1
Sourav Ghosh
  • 133,132
  • 16
  • 183
  • 261