I am new to C and I was trying to programm a dynamic int Array which gets its values via terminal.
I got it to work but it only works for a few numbers before i get the following error: realloc(): invalid next size Aborted. I would like to know why that is
Here is my code so far:
void dynamicIntArray(){
int *dynamicArray = malloc(0);
int length = 0;
printf("Please put in your numbers: \n");
while(1){
int x;
scanf("%d", &x);
if(x == -1){ break; }
else{
dynamicArray = realloc(dynamicArray, sizeof(int));
if(dynamicArray == NULL){ return EXIT_FAILURE; }
dynamicArray[length++] = x;
}
}
}
int main(){
dynamicIntArray();
return 0;
}
reallocis the new size of the array in bytesscanf(), meaning any use ofxafter that line may invoke undefined behavior.