Skip to content

Instantly share code, notes, and snippets.

@gopi487krishna
Last active May 14, 2020 11:04
Show Gist options
  • Save gopi487krishna/d029bf498592941758f01bbcd55c0340 to your computer and use it in GitHub Desktop.
Save gopi487krishna/d029bf498592941758f01bbcd55c0340 to your computer and use it in GitHub Desktop.
This program contains an error that goes undetected during runtime ( memory leak ).Your task is to find why that error occurs and write the correct version of program such that no memory leaks occur.
/*
Task1
There are three classes in this program
1. Demo : Holds a temporary string buffer inside it
2. Base : Parent class with a Demo object inside it ( Polymorphic Base of Derived )
3. Derived : Child class that derives from Base and contains a seperate object of Demo as well
This program contains an error that goes undetected during runtime ( memory leak ).Your task is to find that error and write
the correct version of program such that no memory leaks occur.
Prerequisites:
* Knowledge of C++ classes
* Knowledge of Virtual Functions
* Polymorphism
BONUS POINT : There is one design flaw associated with the program. Think it this way. After allocating memory to b1 there is
a cout call that prints "I am task 1". Problem is if an exception occurs in cout then delete statement would never be called
resulting in a memory leak. Can you guys fix it?
* You must know about exceptions
* You must know about RAII
*/
// You can see the output here https://wandbox.org/permlink/7A3UE6JdYNK6VJ3X
// Hint : The online editor can help you find errors faster if you fiddle with it :)
#include<iostream>
/// This class holds a string buffer inside it
class Demo{
static int active_demo_object_count;
std::string buffer; // Temporary Buffer On most compilers with SBO enabled size is 32bytes
public:
Demo(){std::cout<< "Constructor Invoked - Current Active Objects\t "<<++active_demo_object_count<<"\n";}
~Demo(){std::cout<< "Destructor Invoked - Current Active Objects\t "<<active_demo_object_count--<<"\n";}
};
int Demo::active_demo_object_count=0;
///Polymorphic Base of Derived !!!
struct Base{
Demo d1;
};
///Child class of derived
struct Derived:Base{
Demo d2;
};
int main(){
// You cannot modify this part
Base* b1 = new Derived;
std::cout<<"I am task 1";
// Something strange happens here. Notice carefully
delete b1;
return 0;
}
@tanu-hub
Copy link

In 8th line destructor should be virtual

@SHUBHAM-cybe
Copy link

in line no. 32 and 33 should be the virtual functions in the base class.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment