int matrix with pointers in C - memory allocation confusion

后端 未结 7 1327
春和景丽
春和景丽 2020-12-18 05:01

I\'m having some issues with producing an int matrix without creating memory leaks. I want to be able to make a given (global) matrix into any size dynamically via read_matr

7条回答
  •  情歌与酒
    2020-12-18 05:33

    You're getting memory leaks because you're freeing the first row of the matrix and the list of rows, but none of the 1 to nth rows. You need to call free in a loop.

    There are a couple of alternatives, however: - Allocate sizeof(int*)rows + rowscols*sizeof(int) bytes and use the first bytes for the row pointers. That way, you only have a single chunk of memory to free (and it's easier on the allocator, too) - Use a struct that contains the number of rows. Then you can avoid the row list altogether (saving memory). The only downside is that you have to use a function, a macro, or some messy notation to address the matrix.

    If you go with the second option, you can use a struct like this in any C99 compiler, and again only have to allocate a single block of memory (of size numints*sizeof(int)+sizeof(int)):

    struct matrix {
        int rows;
        int data[0];
    }
    

提交回复
热议问题