int matrix with pointers in C - memory allocation confusion

后端 未结 7 1317
春和景丽
春和景丽 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:36

    Just because the memory has been free'd doesn't mean you can't access it! Of course, it's a very bad idea to access it after it's been free'd, but that's why it works in your example.

    Note that free( *first_matrix ) only free's first_matrix[0], not the other arrays. You probably want some kind of marker to signify the last array (unless you will always know when you free the outer array how many inner arrays you allocated). Something like:

    int** read_matrix(int size_x, int size_y)
    {
        int** matrix;
        matrix = calloc(size_x, 1+sizeof(int*)); // alloc one extra ptr
        for(int i = 0;i

    Then when you're freeing them:

    // keep looping until you find the NULL one
    for( int i=0; first_matrix[i] != NULL; i++ ) {
        free( first_matrix[i] );
    }
    free( first_matrix );
    

提交回复
热议问题