SunAns SunAns - 8 days ago 6
C++ Question

Array return issue

I've made a tree class and a global function. I have made an array in the Tree class function 'insert' which is initialized using another array 'returned' from the global function. The array returned from the global function works fine within that function, however, it gives garbage values upon being assigned to the array(required array) inside the 'insert' function.

Here's the code
(Isn't full due to plagiarism issue)

float *func_calc(...,...,...,...)
{
float decisions[17] = { 0 };
....
.......
......... // Put Values into the 'decisions' array
return decisions;
}

class Tree
{
..
....
.....

insert(...,...,...,...)
{
....
float* fun_array = new float[17];
float min_num = 0;
for (int i = 1; i <= 6; i++)
{
if (i == 1)
{
fun_array = func_calc(...,...,...,...); // same arguments as the insert function arguments
min_num = fun_array[0];
}
else
{
fun_array = entropy(i, array, arraysize, rD);
float num = entfun_array[0];
if (num < min_ent)
{
min_num = num ;
}
}
}
}
};

int main()
{
Tree T1;
T1.insert(... , ... , ..., ... );
}

Answer

You are returning pointer to a temporary, local variable (which causes undefined behaviour), allocated on a stack, which gets deallocated when the function returns. It's better if you create an array first and then pass it to the above function.

Or, an unpreferable, dangerous, method can be to allocate memory on the heap to the decisions array inside the function, to reserve non-local memory :

float *decisions = malloc(17*sizeof(float));

But then, you need to deallocate (free()) the memory allocated using malloc(), otherwise, there will be a memory leak.