MR.Nothing Important MR.Nothing Important - 3 months ago 16
C Question

Realloc crash my programa

Where problem ??, i trying do it with much forms but with realloc giveme errors.

#include<stdio.h>
#include<math.h>
#include<stdlib.h>
#define numbs 10
//math.h para pow();
int main(){
int *array = malloc(numbs * sizeof(int));
if (array == NULL){
printf("Error in memory 1");
return -1;
}
int numbschanger = NULL;
int guardarcounter = NULL;
int *changedirinmemory = NULL;
int counter = NULL; // 0
int saveint = NULL;
int integer;
int numero = NULL;
int res = pow(2,3); // 2 ** 3 = 8, Una potencia.
printf("%d\n",res);
scanf("%d",&numero); // Guardar en la direccion numero.
fflush(stdin);
printf("Los divisores de %d son:\n",numero);
for(integer = 1;integer <= numero;integer++){
if (numero % integer == 0){ // Integer 1 porque si hacemos una divicion de numero / 0 Nos dara o un aviso en la consola de que no se puede dividir entre zero o un crash en el .exe
array[counter] = integer;
printf("%d\n",array[counter]);
counter++;
}
if (counter > numbs){
break;
}
}
printf("Haven\'t problem 01\n");
guardarcounter = counter;
saveint = integer; //Guardada el numero del integer, para que en el nuevo espacio de memoria pueda seguir comprobando "if (numero % integer == 0)"
for(integer;integer <= numero;integer++){
if (numero % integer == 0){
counter++;
}
}
if (numbs < counter){
printf("Campo del crash.");
numbschanger = numbs + counter;
changedirinmemory = realloc(array,numbschanger * sizeof(int)); //Crash hereeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee
if (changedirinmemory == NULL){
printf("Error in memory 2");
return -1;
}
}
printf("Haven\'t problem 02\n");
for(saveint;saveint <= numero;saveint++){
if (numero % saveint == 0){
changedirinmemory[guardarcounter] = saveint;
printf("%d\n",changedirinmemory[guardarcounter]);
guardarcounter++;
}
}
printf("Haven\'t problem 03\n");
if (changedirinmemory != NULL){
free(changedirinmemory);
printf("\n\nEl nuevo espacio de memoria esta libre.");
}
else{
free(array);
printf("\n\nArray Libre.");
}
return 0;
}

Answer

If Weather Vane does not want to…

You problem lies in line 31 if (counter > numbs). That is not enough if counter is equal to numbs

With input 6125346 -> crash
Change line 31 to if (counter >= numbs)
Again with input 6125346 -> works perfectly

But you have a lot of small things in your code that are not fully correct. Please see the comments you got. You can also go to code review for further enlightenment but your code needs to work in the first place, otherwise they'll tear you into fine shreds.