Returning a 2d array from a function

Hello, I need to return a 2D array from a function. I wrote the following code, and it works if I compile it online in C++ environment. However, it produces some odd results when I run it on Arduino Uno.

For the first 50-60 items (“4”). I get the correct number printed. Then, however, the number changes to “4353”, and I can’t see what brings about this change. IT seems as if something gets overflowed, but I fail to notice what.

void setup() {
   Serial.begin (9600);



}

//some function that creates an array
int** getArray () {

  int** insideArray = new int* [3];

  for (int i = 0; i < 3; ++i) {
    insideArray[i] = new int [3];

    for (int k = 0; k < 3; ++k) {
        insideArray[i][k] = i+k;    
    }
      
  }

  return insideArray;
}

void loop() {

  int** outsideArray;
  outsideArray = getArray ();
  Serial.println (outsideArray[2][2]);
   
}

I can't see where you free the memory.
(On a related note, I also can't see where you ensure you've got memory)

Thank you for the answer. What is the correct way to make sure memory is allocated?
I tried:

int **insideArray = new(nothrow) int[3];

but it wont't work.

As for freeing the memory, I can't see where to actually put the delete function. I mean, I need to delete the inside array after the function has transferred the info to the outside array. Does it mean I put it right after return? Then again, will anything be compiled and executed?

Given how little RAM an Uno has, any memory allocating activity is risky business. Why do you need to do so?

You allocate memory 4 times with the 'new' operator. So, you need to use the 'delete' operator 4 times using the pointers that you obtained. I'd do it in the reverse order in which the memory was allocated. Do it at the end of loop.

Regarding checking for availability, it depends what the core does when 'new' can't allocate the memory. I guess you should at least check for 'nullptr'.

This version ran over 32000 cycles:

int RunCount = 0;

void setup()
{
  Serial.begin (115200);
}

//some function that creates an array
int** getArray ()
{
  int** insideArray = new int* [3];

  for (int i = 0; i < 3; ++i)
  {
    insideArray[i] = new int [3];
    for (int k = 0; k < 3; ++k)
    {
      insideArray[i][k] = i + k;
    }
  }
  return insideArray;
}

void loop()
{

  int** outsideArray;
  outsideArray = getArray ();

  Serial.print(++RunCount);
  Serial.print(": ");
  Serial.println (outsideArray[2][2]);

  for (int i = 0; i < 3; ++i)
  {
    delete[] outsideArray[i];
  }
  delete[] outsideArray;
}

Thank you for the correct code. I will both try the code and think about solving the problem another way, avoiding the use of dynamic memory allocation.