I have created a function that deals with an array of pointers and I would like some help proof-reading it. VS seems to accept the code but I want to make sure it doesn't have any "memory leaks" (can someone please explain that term to me?).
Here is my code which is inside a class function to create a new object (modified for privacy reasons):
BaseClass **temp = Objects; //now both temp and Objects point to same data
delete Objects; //Now data Objects currently points to is deleted, Object pointer cannot be used in this state.
//As temp points to same data, it is invalid too.
//Additionally if it was a 2D array allocated with nested new, all actual data is leaked.
NumObjects++;
Objects = new BaseClass*[NumObjects];
for (int i = 0; i < NumObjects - 1; i++)
{
Objects[i] = temp[i]; //Access through invalid pointer temp
}
Err. Smart pointers were common in 2005 and officially became part of standard in 2011. Before that they were avaliable in experimental compiler branches starting roughly from the end of 2009.
I sugges to get used to new standard quickly because there are some new juicy features sheduled to come in 2017.
for(int i = 0; i == NumObjects; i++)
{
Objects[i] = temp[i];
}
THis does not run at all because of faulty condition. Change it to i < NumObjects
return newObj;
What is newObj? I believe you skipped code between line 7 and 9 which changes newObj and initializes last pointer in temp.
This code does not have memory leaks, double delete problems or access to non-owned memory if you fix problems I pointed (right now it copies Objects to temp but does not returns it back). Your original code did contain potential memory leak (but that was offcet by invalid memory access which mostly did the right thing).
BaseClass **temp = new BaseClass*[NumObjects + 1];
for(int i = 0; i < NumObjects; i++)
//Note that temp[NumObjects] is uninitialized
1 2 3 4
NumObjects++
Objects = new BaseClass*[NumObjects];
for(int i = 0; i < NumObjects; i++)
You copy hat uninitialized pointer to Objects. Unless it is initialized elsewere you might have problems
It occurs to me that the sample code leaves out the fact that newObj (defined at the beginning of the function) is appended to temp at the last iteration of the first for loop. It is the first for loop that initializes the temp array.
> I ran a few tests and the following code had no memory leaks!
> why was I told that my code in the first post would produce memory leaks?
perhaps you haven't noticed, but those codes are different
it's quite probable that in your first snip you allocate with new[] but deallocate with delete