Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What happens if i don't free/delete dynamically allocated arrays?

This code is not written bt me! In the class WebServer we overload +=operator. The class uses dynamically allocated array of objects of type WebPage(another class, composition) defined as WebPage *wp;

WebServer & operator +=( WebPage webPage ) {
WebPage * tmp = new WebPage [ count + 1];
for (int i = 0; i < count ; i ++)
tmp [i] = wp[i];
tmp [ count ++] = webPage ;
delete [] wp;
wp = tmp;
return * this ;
}

So we create a new array of dynamically allocated WebPages with extra space for one object, then we assign them the values that wp held, and then the object that we wanted to add to the array. So if i remove delete[] wp; the program still works ok. So what happens if i remove that line of code? And also wp=tmp, what does that mean, is wp only a new name for that dynamically so it would suit the name in the class, but the location in memory is still the same? Or?

like image 759
Stefan Stojkovski Avatar asked Dec 05 '22 09:12

Stefan Stojkovski


1 Answers

So if i remove delete[] wp; the program still works ok. So what happens if i remove that line of code?

You have introduced a memory leak. Each time this operator is invoked the process will waste some portion of its address space until it ultimately runs out of memory.

And also wp=tmp, what does that mean, is wp only a new name for that dynamically so it would suit the name in the class, but the location in memory is still the same? Or?

wp is presumably a member (an instance variable) of WebServer that holds instances of the WebPage objects it serves. So that line is replacing the previous array of web pages with a new value (that includes the web pages just added to the server).

Presumably there are other member functions of WebServer that read the values inside wp and do things with them.

As a general note, you should be aware that this code is extremely badly written because it is not even remotely exception safe, it's doing work that could be avoided with a reasonably smarter implementation and most of all it is using homebrew code instead of standard language facilities like std::vector.

like image 105
Jon Avatar answered Dec 09 '22 13:12

Jon