I'm a bit new to C++, and I'm able to run my code without errors, however, I'm running into memory leaks when I run it through Valgrind, and I can't for the life of me seem to figure out where I'm leaking! Here's my error message:
==22902== in use at exit: 72,728 bytes in 2 blocks
==22902== total heap usage: 4 allocs, 2 frees, 73,816 bytes allocated
==22902==
==22902== 24 bytes in 1 blocks are definitely lost in loss record 1 of 2
==22902== at 0x4C2E80F: operator new[](unsigned long) (in /usr/lib/valgrind/vgpreload_memcheck-amd64-linux.so)
==22902== by 0x401086: Bar::Bar(int, std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> > const&, unsigned int) (Bar.cpp:10)
==22902== by 0x400F76: main (Foo_main.cpp:20)
I have a class, Foo, which are used as "attachments" to the Bar class. Bar inherits from foo. It has two private members, id_ and name_, and the destructor and use() are declared as virtual in the header file.
#include "Foo.h"
#include<iostream>
using std::cout;
using std::endl;
using std::string;
Foo::Foo(int id, const string& name) :
id_(id),
name_(name){}
Foo::~Foo() {}
int Foo::id() const { return id_; }
string Foo::name() const { return name_; }
void Foo::use() const {
cout << "Using Foo #" << id_ << ", " << name_ << endl;
}
Bar has two private members, num_attachments_ (unsigned int) and attachments_ (Foo**)
#include "Bar.h"
#include <iostream>
using std::cout;
using std::endl;
Bar::Bar(int id, const std::string& name, unsigned int num_attachments) :
Foo(id, name),
attachments_(new Foo*[num_attachments]),
num_attachments_(num_attachments) {
// explicity null out each entry in the new array
for (unsigned int i=0; i<num_attachments; ++i) {
attachments_[i] = NULL;
}
}
void Bar::use() const {
cout << "Using Bar #" << id() << endl;
for (unsigned int i=0; i<num_attachments_; ++i) {
if (attachments_[i] != NULL) {
attachments_[i]->use();
}
}
}
(Note: Some of the code that I know isn't causing leaks is commented out). I suspect that the issue is in Bar's use() function, but I'm not quite sure what's missing!
Finally, here's the main function:
Foo* f = new Bar(1, "foobar", 3);
f->use();
delete f;
I can, of course, upload the entire program at request (although I feel like the problem is probably obvious and I'm just missing something completely). Any help would be awesome!