Problem with dynamic allocation

Asked

Viewed 193 times

2

I need to make a code where the user fills in an array as many times as he wants, but the code stops running. If I register only 3 values, like (1) (2) (3) it works normally, but in some moments (there is no default) the program stops running. I couldn’t find my fault.

Follows the code:

#include<stdio.h>

main(){
int *vetor, i, d, contador=0; 
char c;
vetor=NULL;
do{
    if(contador==0)
        vetor=malloc(1*sizeof(int));
    else
        realloc(vetor,1*sizeof(int));
printf("Digite um valor para salvar no vetor: ");
scanf("%d", &d);
*(vetor+contador)=d;
contador++;
printf("Deseja cadastrar mais um numero? ");
scanf(" %c", &c);
system("pause");
} while(c == 's' || c == 'S');
system("cls");
for(i=0; i<contador; i++)
    printf(" (%d) ", vetor[i]);
}
  • your realloc is relocating the same space try realloc(vetor,tamanho*sizeof(int)); where for each loop the tamanha increments +1

1 answer

2


The main problem is that the relocation is using the same size always, is not increasing and is not assigning to a variable, this relocation is lost, this generates the error. There are better ways to solve this, but for an exercise is good. Change:

vetor = realloc(vetor, sizeof(int) * contador + 1);

Behold working in the ideone. And in the repl it.. Also put on the Github for future reference. I rephrased to a way that I like better and much more organized. In real code I would do a little different yet

  • Really, I changed here and it worked, and best of all: I understood why I was wrong! Thank you very much, Hug!

  • If the realloc()fail and return NULL you lose the reference to vetor. It is preferable to use an auxiliary variable: vetortmp = realloc(vetor, ...); if (!vetortmp) /* erro; vetor ainda esta valido */; vetor = vetortmp;

Browser other questions tagged

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