tomdavies
tomdavies

Reputation: 1976

Freeing the memory - two dimensional array

I use Visual C++ 2010 and I'm trying to use free() with two dimensional array:

#include <stdio.h>
#include <stdlib.h>
#define SIZE 8


int main(){

    int **matrix = (int**)malloc(sizeof(int*)*SIZE);
    int i;
    for(i=0; i<SIZE; i++){
        matrix[i] = (int*)malloc(sizeof(int)*SIZE);
    }
    for(i=0; i<SIZE; i++){
        free(matrix[i]);
    }
    free(matrix);
    getch();
    return 0;
}

Am I doing this right?

Regards.

Upvotes: 1

Views: 155

Answers (2)

Heisenbug
Heisenbug

Reputation: 39194

Basically it should be right.

Btw you don't need to call malloc for each row of the 2d array you are trying to allocate (unless you have specific reasons to do that).

You can use just one malloc and one free:

malloc(sizeof(int*)*ROW_NUM * COL_NUM);

Using a single call to malloc has also the benefits to allocate continuosly in memory the elements of your matrix.

Upvotes: 7

bdwain
bdwain

Reputation: 1745

Looks like it. Although you can and probably should (for efficiency purposes) do just one malloc and one free as shown here

If you don't need to be in C explicitly, it might be worth taking a look at vectors to handle the memory for you.

Upvotes: 2

Related Questions