Home > database >  Memory issue when freeing 2D arrays
Memory issue when freeing 2D arrays

Time:03-28

2D Array creation phase :

int **table = new int*[10];
for (int a = 0; a < 10; a  )
{
    table[a] = new int[10];
    for(int b = 0; b < 10; b  ){
        table[a][b] = 0;
    }
}

2D Array deletion phase :

for (int i = 0; i < 10; i  )
{
    delete [] table[i];
}
delete [] table;

I noticed something while debugging my code with GDB. All values from table[0][0] to table[0][3] are garbage but all values from table[0][4] to table[0][9] are all 0. This problem is Valid for all pointers from table[0] to table[9].

Then I thought there was a problem with GDB and I printed table[0][0] and table[0][5] to the screen. Indeed the value of table[0][0] is garbage, the value of table[0][5] is 0.

My question is does c actually freeing this data?

CodePudding user response:

Yes, the data is actually being freed. If you dereference a pointer after its value is freed, you get undefined behaviour which might be its original value or some other garbage value.

  • Related