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.