Problem to create a linked list in C

0

Hello, I'm trying to create a linked list automatically, that is, it will be created inside a for . But for some reason I get the error segmentation fault, follow the code:

no *lista, *cabeca;
  int n, r1, *r2;
  int i,j;
  cabeca = malloc(sizeof(no));
  cabeca->prox = NULL;
  cabeca = lista;
  scanf("%d", &n);
  for (i = 0; i < n; i++){
    lista = malloc(sizeof(no));
    lista->valor = n-i;
    lista->prox = cabeca->prox;
    cabeca->prox = lista;
  }
//esse scanf será outra funcao do meu codigo
  scanf("%d", &r1);
  r2 = malloc(r1*sizeof(int));
  for(j = 0; j < r1; j++){
    scanf("%d ", &r2[j]);
  }
    
asked by anonymous 02.09.2016 / 20:47

1 answer

1

Let's see what your code does. First we have this:

no *lista, *cabeca;

In this line above, you declare the lista and cabeca pointers, not initialized. Then we have this:

cabeca = malloc(sizeof(no));
cabeca->prox = NULL;

Here, you make cabeca point to an allocated memory region to save a node and sets the next node to be NULL , so as not to leave the uninitialized pointer. However, the reference cabeca->valor remains uninitialized.

Next we have this:

cabeca = lista;

OPS! Here you are putting% of the contents of an uninitialized pointer in%. As the old reference is lost, we also have a memory leak.

Now inside cabeca , we have this:

lista = malloc(sizeof(no));
lista->valor = n-i;

You are creating a new node and putting it in the for variable. All right.

Soon after:

lista->prox = cabeca->prox;

Remember that cabeca was an uninitialized pointer? Well, it means that cabeca will give a segmentation fault!

Next:

cabeca->prox = lista;

If this were to run, it would be another segmentation flaw.

Finally, this last bit, I think it's correct:

scanf("%d", &r1);
r2 = malloc(r1*sizeof(int));
for(j = 0; j < r1; j++){
  scanf("%d ", &r2[j]);
}

I think what you wanted was this:

no *lista = NULL, *cabeca = NULL;
int i, j, n, r1, *r2;
scanf("%d", &n);
for (i = 0; i < n; i++) {
    lista = malloc(sizeof(no));
    lista->valor = n - i;
    lista->prox = cabeca;
    cabeca = lista;
}
scanf("%d", &r1);
r2 = malloc(r1 * sizeof(int));
for (j = 0; j < r1; j++) {
    scanf("%d ", &r2[j]);
}
    
03.09.2016 / 02:40