I have written the folowing code in C:
#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 0;
}
int main(void){
int numb = 10;
int * array = calloc(1, sizeof(int));
func(numb, array);
for(int j = 0; j < numb; j++){
printf("%d \t", array[j]);
}
free(array);
return 0;
}
On the first computer the output is as expected:
1 2 3 4 5 6 7 8 9 10
Now if I compile and run the same program on another computer, it outputs random integer values. What am I missing here? What do I do wrong? Why does the very same program have a different behaviour on different computers?
The behavior of this program is undefined. If it prints out what you expect on any computer, it's purely by coincidence.
int * array = calloc(1, sizeof(int));
func(numb, array);
You're passing array
by value here, meaning whatever func
does to it is invisible to the outer scope. Note that realloc
is not guaranteed to return the same pointer, so you need to expect that array
will be changed during the course of the call. Try passing a pointer to array
instead.
int func(int n, int ** data){
for(int i = 1; i <= n; i++){
*data = realloc(*data, i * sizeof(int));
(*data)[i - 1] = i;
}
return 0;
}
...
func(numb, &array);