I am trying to fill a dynamically generated array using a for loop and make it bigger whenever needed using realloc(). However, when realloc is called several times on the memory, it replaces some values, especially the first and last few with seemingly random numbers.
This is the code I tested the said with:
#include <stdio.h>
#include <stdlib.h>
void fill(int * array, int size, int number_of_values) {
for (int i = 0; i < number_of_values; i++) {
if (i == size) {
size *= 2;
array = realloc(array, sizeof(int) * size);
}
array[i] = 100;
}
}
int main() {
int *array;
int number_of_values = 21;
int size = 5;
array = malloc(sizeof(int) * size);
fill(array, size, number_of_values);
for (int i = 0; i < number_of_values; i++) {
printf("%i ", array[i]);
}
}
I tried reimplementing the code several times and looked at the array directly after assigning 100 to it, but all the values are assigned correctly at first and then change somehow. I also observed, that said behavior only seems to happen when there are more than 20 items assigned to the array in the loop.
The output of the program normally looks something like this:
10425976 10436440 100 100 100 100 100 100 100 100 100 100 100 100 100 100 100 100 100 100 134217736
Whereas when I set number_of_values to 20 and therefore only assign 20 values, the output looks like the following:
100 100 100 100 100 100 100 100 100 100 100 100 100 100 100 100 100 100 100 100
I also looked through some references of the realloc function, but as far as I'm concerned, I used it correctly.
realloc. (You changefill'sarray, but notmain's.) You are using a pointer that's no longer valid.array = realloc(array,...)is a memory leak in case thereallocfails. You should always assign the return value ofreallocto another pointer to check it.array = realloc(array, sizeof(int) * size);setarrayto the new pointer?fill'sarray. Notmain's, though. There are two variables namedarray, and you are only changing one of them.