I am coding a function that will return a 2D array. This leds me to think about the implications of this in C# (with garbage collection) and in C++(no GC)
(Why in both-you may ask: I am now writing it on a windows platform with C# but in some months I will implement my algorithms on an embedded device using C++)
So basically I have a 2D array say table, and through a function I assigned to it the return value. My question is: what happen to the original piece of memory that hold the original table??
Now to the code: In C#
using System;
public class Test
{
public static void Main()
{
int[,] table= new int [10,10]; //Here some memory is separated for table
int[,] table= createTable(10,10); //Here the return value of createTable is assigned to the original value
//WHAT HAPPENED TO THE ORIGINAL MEMORY THAT table HAD?
printTable(table,10,10); //disregard this. Not that important
}
public static int[,] createTable(int rows, int columns)
{
int[,] t = new int[rows,columns];
for(int i=0;i<rows;i++)
for(int j=0;j<columns;j++)
t[i,j]=(i+j);
return t;
}
public static void printTable(int[,]t, int rows, int columns)
{
for(int i=0;i<rows;i++)
for(int j=0;j<columns;j++)
Console.WriteLine(t[i,j]);
foreach( var im in t)
Console.WriteLine(im);
}
}
(Please don't tell me that the first new int is not necessary, etc. It is necessary for the question, it could be replaced by calling createTable twice)
I am guessing that in C#, the garbage collector takes care of this and I don't have to worry?
Now in C++
#include <cstdio>
#include <cstdlib>
int** createTable(int rows, int columns){
int** table = new int*[rows];
for(int i = 0; i < rows; i++) {
table[i] = new int[columns];
for(int j = 0; j < columns; j++){ table[i][j] = (i+j); }// sample set value;
}
return table;
}
void freeTable(int** table, int rows){
if(table){
for(int i = 0; i < rows; i++){ if(table[i]){ delete[] table[i]; } }
delete[] table;
}
}
void printTable(int** table, int rows, int columns){
for(int i = 0; i < rows; i++){
for(int j = 0; j < columns; j++){
printf("(%d,%d) -> %d\n", i, j, table[i][j]);
}
}
}
int main(int argc, char** argv){
int** table = createTable(5, 5);
table = createTable(10,10);
printTable(table, 10, 10);
freeTable(table, 10);
return 0;
}
What happened to the original memory hold by table (5x5). Does it create a memory leak when table get assigned the 10x10 table?? how do I avoid this?