Hello everybody,
I want to write a function which takes an array previously created with allocated memory with a given number of rows and columns. This function should increase the number of rows and columns, fill the array and update it in the original array, also the number of rows and columns should be updated. I created the function update() but I have two problems:
1. When I print the updated array inside the function update(), everything looks ok. But when I print the array in the main() the result is not he expected one. It is curious for me that the number of rows and columns are being properly updated but the array is not updated.
2. I am creating the array MATRIX with malloc() in the main(). Then the function update() is taking MATRIX is reallocating and doing everything well, but I still need to liberate the memory created with malloc(), if I put the instruction to liberate the memory in the main, I get an error saying that I am trying to free memory which was not allocated.
Follows the code that I wrote:
Code:
int main() {
int rows=1, cols=1;
int * MATRIX = (int*)malloc(rows * cols * sizeof(int));
*MATRIX=1;
update(&rows, &cols, MATRIX);
printf("\n\n (IN THE MAIN) rows=%d\n\t\t\tcolumns=%d\n",rows, cols);
printf("\n Printing the array in the main()\n");
for (int i=0;i<rows;i++){
for (int j=0;j<cols;j++){
printf("%3d",*(MATRIX + i*cols + j));
}
printf("\n");
}
//free(MATRIX);
return 0;
}
void update(int * nrow, int * ncol, int * Matrix){
int Nrow=*nrow*3;
int Ncol=*ncol+1;
int * NewMatrix=(int*)malloc(Nrow * Ncol * sizeof(int));
for (int i=0;i<Nrow;i++){
for (int j=0;j<Ncol;j++){
*(NewMatrix+ i*Ncol +j)=i*Ncol + j;
}
}
Matrix=(int *)realloc(Matrix,(Nrow * Ncol * sizeof(int)));
for (int i=0;i<Nrow;i++){
for (int j=0;j<Ncol;j++){
*(Matrix+ i*Ncol +j)=*(NewMatrix+ i*Ncol +j);
}
}
free(NewMatrix);
printf("Printing the result INSIDE the function\n");
for (int i=0;i<Nrow;i++){
for (int j=0;j<Ncol;j++){
printf("%3d\t",*(Matrix+ i*Ncol +j));
}
printf("\n");
}
*nrow=Nrow;
*ncol=Ncol;
printf("\nrows=%d\ncols=%d",*nrow,*ncol);
}
The output obtained is:
Printing the result INSIDE the function
0 1
2 3
4 5
rows=3
cols=2
(IN THE MAIN) rows=3
columns=2
Printing the array in the main()
0 0
268767505805306368
5313504 1
And if I enable the line free(MATRIX) in the main() then I get the following error:
UPDATING_ARRAYS(8726,0x1000a95c0) malloc: *** error for object 0x10210c720: pointer being freed was not allocated.
Thanks beforehand for your help.