I have a C++ class with this data member:
The memory for this variable is properly allocated and the variable is usable throughout the entire program, but after using the overloaded plus operator (implemented as a friend function) my program gets an Invalid Allocation Size error.
Here is an example of a line that errors. s1, sa3, and sa4 are all properly created stringArray objects:
Here is the operator+ function:
Code:
stringArray& operator+(const stringArray& arr1, const stringArray& arr2)
{
stringArray temp(arr1.count + arr2.count);
for(size_t i = 0; i < arr1.count; i++)
{
if(arr1.data[i] != NULL)
{
temp.addString(arr1.data[i]);
}
}
for(size_t i = 0; i < arr2.count; i++)
{
if(arr1.data[i] != NULL)
temp.addString(arr2.data[i]);
}
return temp;
}
temp gets correctly created and has all of the strings created, but once the function returns, the data variable is an undefined pointer.
I think the issue is that temp is created on the stack. I do not know what convention C++ uses to return object, but I assume that they put the memory location of the object in the return register. If this is the case, I understand that when the stack was decremented, that the memory location is lost.
I am hoping someone can explain to me how other people create the operator+ function when they have a pointer in their class, it seems like the only thing to do would be to return a point (created in heap) and take the memory leak.
Thank you.