c - How to free a two dimensional array allocated memory using int ** ptr -
how free 2 dimensional array using function allocated memory using int ** ptr?
for example use allocarray( &ptrarray, row, column);
allocate array. proper procedure free allocated memory using function: void freearray( int *** pa, int row, int column)
#include <stdio.h> #include <stdlib.h> void allocarray( int *** pa, int row, int column) { int i, j, count; *pa = (int **) malloc(row * sizeof(int *)); (int =0; i<row; ++i) { (*pa)[i] = (int *) malloc( column * sizeof(int)); } // note pa[i][j] same *(*(pa+i)+j) count = 0; (i = 0; < row ; i++) (j = 0; j < column; j++) (*pa)[i][j] = ++count; // or *(*(pa+i)+j) = ++count (i = 0; < row; i++) { (j = 0; j < column; j++) { printf("%d ", (*pa)[i][j]); } printf("\n"); } } // how free 2 dimensional array allocated memory using int ** ptr? void freearray( int *** pa, int row, int column) { } void test_array_allocation() { int i, j; int row = 3, column = 4; int ** ptrarray; allocarray( &ptrarray, row, column); printf("test_array_allocation\n"); (i = 0; < row; i++) { (j = 0; j < column; j++) { printf("%d ", (ptrarray)[i][j]); } printf("\n"); } freearray(&ptrarray, row, column); // free allocated memory } int main(int argc, const char * argv[]) { test_array_allocation(); return 0; }
if doing it, can show me how this?
here's how implement this. i've never implemented 2d arrays in c before, fun bit of code write.
#include <stdio.h> #include <stdlib.h> void* xmalloc(size_t n) { void* p = malloc(n); if (p == null) { printf("i handle errors!\n"); exit(exit_failure); } return p; } int** alloc2darray(unsigned rows, unsigned cols) { int** r = xmalloc(sizeof(int*) * rows); (int = 0; < rows; i++) r[i] = xmalloc(sizeof(int) * cols); return r; } void print2darray(int** a, unsigned rows, unsigned cols) { (int = 0; < rows; i++) { (int j = 0; j < cols; j++) printf("%4d", a[i][j]); putchar('\n'); } } void free2darray(int** x, unsigned rows) { (int = 0; < rows; i++) free(x[i]); free(x); } int main(void) { int** x = alloc2darray(10, 14); (int = 0; < 10; i++) (int j = 0; j < 14; j++) x[i][j] = i*j; print2darray(x, 10, 14); free2darray(x, 10); return 0; }
another tip might not aware of: can use valgrind
on gnu/linux verify deallocated correctly:
==9322== heap summary: ==9322== in use @ exit: 0 bytes in 0 blocks ==9322== total heap usage: 11 allocs, 11 frees, 640 bytes allocated ==9322== ==9322== heap blocks freed -- no leaks possible ==9322== ==9322== counts of detected , suppressed errors, rerun with: -v ==9322== error summary: 0 errors 0 contexts (suppressed: 0 0)
Comments
Post a Comment