简体   繁体   中英

Freeing a 2-d char array

After using this function to allocate a 2-d array:

char** make_matrix(int M, int N)
{
    char** MAT = (char**)malloc(M * sizeof(char));
    for (int i = 0; i < M; i++)
    {
        MAT[i] = (char*)malloc(N * sizeof(char));
    }
    return MAT;
}

I found that trying to free(M[0]) causes an assertion failure. All that I can find relating to freeing 2-d arrays use int instead of char . Yet replace every char with int above and the assertion failure disappears. Why is this, and how can I then free the entire 2-d array?

You are allocating too little memory for MAT . Change relevant line to:

char** MAT = (char**)malloc(M * sizeof(char*));

This is because MAT is array of pointers, not characters. Since your code did not allocate enough memory, it was likely writing outside of array bounds and corrupting memory.

It could work with integers because they are bigger, so with some luck you could have been allocating just enough memory (at least on 32 bit machine).

The first malloc call is M * sizeof(char) instead of sizeof(char *). The sizeof(char) would be 1 byte, the size of a char* is likely 4 bytes.

Edit: I see someone beat me to the punch. Accept the other guy's answer.

You should iterate through all the rows of the matrixes and free them first, and then finally the MAT

something like this:

void free_matrix(int M)
{
    for (in i = 0; i < M; i++)
    {
        free(MAT[i]);
    }
    free(MAT);
}

To release the space (assuming it is correctly allocated), you need a call to free() corresponding to each call to malloc() .

void destroy_matrix(char **MAT, int M)
{
    for (int i = 0; i < M; i++)
        free(MAT[i]);
    free(MAT);
}

Your code works when you replace char with int because sizeof(int) == sizeof(int *) on your (32-bit) system. It's largely by coincidence; you'd be in trouble again on a 64-bit system.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM