Problem for creating a list linked in C

Asked

Viewed 58 times

0

Hello, I’m trying to create an automatically linked list, IE, it will be created within a for. But for some reason I keep getting 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]);
  }
  • edit your question by formatting the code...in the edit window menu has a key open/close icon...select the lines of code with the mouse and click the key open/close icon, otherwise your code becomes unreadable

1 answer

1

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

no *lista, *cabeca;

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

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

Here, you do it cabeca point to an allocated memory region to store a node and set the next node to be NULL, not to leave the pointer initialized. However, the reference cabeca->valor still not initialized.

Next we have it:

cabeca = lista;

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

Already inside the for, we have it:

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

Is creating a new node and putting in the variable cabeca. All right yet.

Right after:

lista->prox = cabeca->prox;

Do you remember that cabeca was an uninitialized pointer? Yeah, that means cabeca->prox will give a segmentation failure!

Next:

cabeca->prox = lista;

If it were to perform, it would be another segmentation failure.

Finally, this last part, I think is 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]);
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.