I am currently messing around with c. I have a few hiccups in using pointers and syntax.
Below I try to create an array of pointers for whole arrays, and then direct each pointer to an array created through malloc ().
After creating the arrays, I then loop through each cell, assigning a value.
Now it all works, but when it comes to using free () to recover memory, the program crashes.
I noticed that if I malloc () the memory of the array, and then immediately calls free () on them, the program runs without problems. When, however, I malloc () assign the values and THEN free (), a crash occurs. (Segmentation error).
Below is the code that works, malloc (), and then immediately free () ing
int (*ptrArr[5])[5]; for(int i=0; i<5; i++) ptrArr[i] = malloc(sizeof(int) * 5); for(int i=0; i<5; i++) printf("ptrArr[%d][%x]->[%x]\n", i, &ptrArr[i], &*ptrArr[i]); printf("\n"); for(int i=0; i<5; i++){ for(int j=0; j<5; j++){ printf("[%x](%2d) | ", &*ptrArr[i][j], *ptrArr[i][j]); } printf("\n"); } for(int i=4; i>=0; i--) free(ptrArr[i]);
the above runs as I expected, but when I assign values to the cells and then try and call later, segmentation fails:
int (*ptrArr[5])[5]; for(int i=0; i<5; i++) ptrArr[i] = malloc(sizeof(int) * 5); for(int i=0; i<5; i++) printf("ptrArr[%d][%x]->[%x]\n", i, &ptrArr[i], &*ptrArr[i]); printf("\n"); for(int i=0; i<5; i++){ for(int j=0; j<5; j++){ printf("[%x](%2d) | ", &*ptrArr[i][j], *ptrArr[i][j]); } printf("\n"); } int loop = 5; for(int i=0; i<5; i++){ for(int j=0; j<5; j++){ *ptrArr[i][j] = (loop + (i*j)); ++loop; } } printf("\n"); for(int i=0; i<5; i++){ for(int j=0; j<5; j++){ printf("[%x](%2d) | ", &*ptrArr[i][j], *ptrArr[i][j]); } printf("\n"); } for(int i=4; i>=0; i--) { printf("Freeing ptrArr[%x]\n", i); free(ptrArr[i]); }
I think I either misunderstand
int (*ptrArr[5])[5];
which I intended was an array of 5 pointers, each of which pointed to an integer array, or im incorrectly assigning values to the cells correctly, instead distorting the memory, due to which the free () function fails.
Any help would be appreciated, I hope the question is clear and concise.
Thanks.