I post this sample code in order to explain my problem. I'm trying to passing among functions a pointer to integer. If you compile & run this code you'll see that strange numbers appears and I can't get why. I think it's a bad use of realloc()
. If anybody could give a hint or maybe redirect me to some questions similar to this I'll appreciate. I search for this problem but I can't find anything similar.
#include <stdio.h>
#include <stdlib.h>
void myFunction(int **output);
int main(){
int *indices;
myFunction(&indices);
printf("{");
for(int i=0;i<10;i++){//suppose also for some mysterious reasons that I know min_size in the main
printf("%i,", indices[i]);
}
printf("}\n");
return 0;
}
void myFunction(int **output){
int size = 130;//allocating big amount of space
int* indices = malloc(sizeof(int)*size);
//...start doing mysterious stuffs....
int min_size = 10;
for(int i=0;i<min_size;i++){
indices[i] = i;//just for saving something
}
//...end doing mysterious stuffs...
//now for some reasons I know I need only min_size elements and all other are wasting space so I reallocate
indices = realloc(indices,min_size);//resizing in order to save space
*output = indices;
}
You are using realloc incorrectly. The size of the reallocated extent must be
min_size * sizeof( int )
Here you are
#include <stdio.h>
#include <stdlib.h>
void myFunction(int **output);
int main( void )
{
int *indices;
myFunction(&indices);
printf("{");
for(int i=0;i<10;i++){//suppose also for some mysterious reasons that I know min_size in the main
printf("%i,", indices[i]);
}
printf("}\n");
return 0;
}
void myFunction(int **output){
int size = 130;//allocating big amount of space
int* indices = malloc(sizeof(int)*size);
*output = indices;
// ^^^^^^^^^^^^^^^
//...start doing mysterious stuffs....
int min_size = 10;
for(int i=0;i<min_size;i++){
indices[i] = i;//just for saving something
}
//...end doing mysterious stuffs...
//now for some reasons I know I need only min_size elements and all other are wasting space so I reallocate
indices = realloc(indices, min_size * sizeof( int ) );//resizing in order to save space
//^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
if ( indices ) *output = indices;
//^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
}
The program output is
{0,1,2,3,4,5,6,7,8,9,}