The following code contains a memory leak.
What constitutes that leak?
What would be a fix to the problem?
#include <vector>
class Object
{
public:
Object(int id) : _id(id) {}
int id() const { return _id; }
private:
int _id;
};
class ObjectContainer
void add_object(Object* o) { _container.push_back(o); } private:
using _Container = std::vector<Object*>;
_Container _container;
int main()
ObjectContainer container;
Object* o = new Object(666);
container.add_object(o);
return 0;
}
in main() —> creates object on the heap but dosen’t delete it befor program ends, meaning the object will continue to take up memory even after the program is done using it.
fix —> make sure object is deleted after using it use container of objects combined with destructor
The following code fragment contains a bug. What is the bug? Describe it.
#include <iostream>
std::vector<int> my_vector = { 1,2,3 };
std::cout << my_vector[3] << std::endl;
attempts to access an element at index 3 of the vector “my_vector” —> vector has only 3 elemets with index 0,1,2 container does not check if index is whithin range of valid indices. It’s accessing memory that is out of the bounds of the vector; therefor —> Output will be unexpected behaviour.
Last changed2 years ago