Alright, so this code works, and does what it is supposed to (I was just messing around with structs to get a feel for them since I have never really used them before)Code:#include <stdio.h> #include <stdlib.h> struct test_struct { double **array; int test; }; int main() { struct test_struct kyle; kyle.test = 18; printf("test = %d\n",kyle.test); kyle.array = (double **) malloc(5*sizeof(double *)); if (kyle.array == NULL) { printf("fail"); } int i = 0; for (i = 0; i < 5; i++) { kyle.array[i] = (double *) malloc(10*sizeof(double)); if ( kyle.array[i] == NULL) { printf("fail2"); } } int j = 0; for (i = 0; i < 5; i++) { for(j = 0; j < 10; j++) { kyle.array[i][j]=i*j; } } for (i = 0; i < 5; i++) { for(j = 0; j < 10; j++) { printf("%d\t",(int) kyle.array[i][j]); } printf("\n"); } for (i = 0; i < 5; i++) { free(kyle.array[i]); } free(kyle.array); }
However, if in the part where I free the memory allocated for array, I use j instead of i, I get a segfault. Why would it matter which one of the indices I use, since I initialize it to 0 at the start and hard code the limits?
ie, if the bolded section above is replaced with
it segfaults. Now I am sure this is just a trivial little thing I am missing, but I can't seem to see it.Code:for (j = 0; j < 5; j++) { free(kyle.array[i]); AHA! where did that i come from... ^_^ } free(kyle.array);
EDIT: and I just saw it. Ignore me...



LinkBack URL
About LinkBacks


