Your program has undefined behaviour. So, it is possible that it has different behaviours even in the same computer... Let me explain:
#include <stdio.h>
#include <stdlib.h>
int func(int n, int * data){
for(int i = 1; i <= n; i++){
// HERE, YOU CHANGE THE VALUE OF data FOR THE NEW
// VALUE RETURNED BY REALLOC. As the value ov array
// was copied on entry, it is not known outside of
// func()
data = realloc(data, i * sizeof(int));
data[i - 1] = i;
}
return 0;
// AFTER THIS POINT THE ORIGINAL (the passed in value
// to func() is not valid anymore
}
int main(void){
int numb = 10;
int * array = calloc(1, sizeof(int));
func(numb, array);
// at this point, the value of array is not valid,
// in case the value realloc() has returned inside
// func() has changed.
for(int j = 0; j < numb; j++){
printf("%d \t", array[j]);
}
// THIS IS ALSO INCORRECT.
free(array);
return 0;
}
A workaround to your problem is that you return the
new value back (the one returned by calloc()), as in
#include <stdio.h>
#include <stdlib.h>
int *func(int n, int * data){
for(int i = 1; i <= n; i++){
data = realloc(data, i * sizeof(int));
data[i - 1] = i;
}
return data;
}
int main(void){
int numb = 10;
int * array = calloc(1, sizeof(int));
// now array continues to be bvalid after the call to func().
array = func(numb, array);
for(int j = 0; j < numb; j++){
printf("%d \t", array[j]);
}
free(array);
return 0;
}
By the way, in order to be optimum, and as you know the final value that i
will take in func()
(n
), you should write func()
to make only one call to realloc()
and this will be faster than reallocating once per value.
int *func(int n, int *data) {
data = realloc(data, n * sizeof *data);
for (int i = 1; i <= n; i++)
data[i-1] = i;
return data;
}