I am new to using malloc in C. I was trying to declare a dynamic array of structures and later free it, similary a 2D aray and free it. I am using gcc to compile the code.
First question is regarding using array of structures,
struct OPinfo { long NLocal; double ReFrame,ImFrame,lcl_ReFrame,lcl_ImFrame,lcl_SqFrame; }; struct OPinfo *OPSTR; void declare_local_structure() { OPSTR = (struct OPinfo*) malloc(NBinsR * sizeof(struct OPinfo)); int i =0; while(i<NBinsR) { OPSTR[i].NLocal = 0; OPSTR[i].ReFrame = 0.0; OPSTR[i].ImFrame = 0.0; OPSTR[i].lcl_ReFrame = 0.0; OPSTR[i].lcl_ImFrame = 0.0; OPSTR[i].lcl_SqFrame = 0.0; i++; } } void free_local_structure() { fprintf(stderr,"%d %d\n",*OPSTR,OPSTR); free(OPSTR); }
The fprintf(..OPSTR) part is giving same address in declare_local_structure() and free_local_structure() indicating no pointer mishap in the mean time. If I comment out the free(OPSTR) part, the program works well. Otherwise, it runs and at the end, where free_local_structure() is called, it is giving the following error. * Error in `./a.out': free(): invalid size: 0x0000000002d2fd40 *
In the same program in another part I am using a 2D array of pointers, which I declared by,
double **Gxy, **GxyRot; Gxy = (double**) malloc((NBinsXY) * sizeof(double *)); GxyRot = (double**) malloc((NBinsXY) * sizeof(double *)); for(j=0; j<NBinsXY; j++) { Gxy[j] = malloc(NBinsXY * sizeof(double)); GxyRot[j] = malloc(NBinsXY * sizeof(double)); }
and free by,
for(l=0;l<NBinsXY;l++) {
free(Gxy[l]);
free(GxyRot[l]);
}
free(Gxy);
free(GxyRot);
This again gives the same error above but if I free by,
free(*Gxy);
free(*GxyRot);
free(Gxy);
free(GxyRot);
the program runs without error.
Where are the errors? I tried "valgrind", but could not understand the output. Another point is the program gave error while compiling with C99.
gcc -std=c99 *.c headers/*.h -lm