So, I have a pointer which need to increase it's "length" until the user insert a negative number or "e". It starts with the length of "1", via a malloc()
then I use into a do{...} while(...)
loop the realloc()
function to increase its lenght. Here's the code:
int *array = malloc (sizeof(int) * 1);
bool exit = false;
int lastIndex = 0, value;
do {
printf ("Insert a positive number. Insert a negative number or \"e\" to exit: ");
int scanf_result = scanf("%i", &value);
if (scanf_result) {
if (value >= 0) {
array[lastIndex] = value;
lastIndex++;
array = (int*) realloc (array, lastIndex * sizeof(int));
} else {
exit = true;
}
} else {
exit = true;
}
} while (!exit);
I can't figure out why after the 7th cicle it exit with the error realloc(): invalid next size
.
Any idea? Thanks in advice for help.