I am trying to generate objects to add to a vector for use in populating a database, when doing so I noticed a memory leak, I am sure it's something to do with the way I am adding the objects to the Vector due to the fact if I do not add any objects to the vector the function works as expected with no leaks. Where have I gone wrong?
I have tried moving the unique_ptr, same result.
I have found with this code, not all memory will be de-allocated each run of database::populate, after many executions of the populate function almost 400 mb of memory will not be de-allocated, why?
main.cpp
#include <iostream>
#include "database.h"
int main()
{
std::vector<string> cols{"name", "score" };
while (true) {
std::getchar();
database::populate("test", cols, 1000000);
}
}
database.h
#include <string>
#include <vector>
using std::string;
class database {
public:
static void populate(const string table, std::vector<string> cols, int limit);
};
database.cpp
#include "database.h"
#include "model.h"
#include <memory>
#include <random>
#include <iostream>
typedef std::vector<std::shared_ptr<Model>> modelContainer;
static const char alphanum[] =
"0123456789"
"ABCDEFGHIJKLMNOPQRSTUVWXYZ"
"abcdefghijklmnopqrstuvwxyz";
//temporary
int alphaLen = std::size(alphanum) - 1;
std::random_device rd;
std::mt19937 gen(rd());
int random(int min, int max) {
std::uniform_int_distribution<>rng_dice(min, max); return rng_dice(gen);
}
string randstring(int len) {
string str = "";
while (len--) {
int index = random(0, alphaLen);
str += alphanum[index];
}
return str;
}
void database::populate(const string table, std::vector<string> cols, int limit) {
modelContainer models;
std::shared_ptr<Model> e;
for (int i = 0; i < limit; i++) {
e = std::make_shared<Model>(table);
for (int j = 0; j < cols.size(); j++) {
e->addVal(cols[j], randstring(5));
}
models.push_back(std::move(e)); //Leak??
}
std::cout << "done!" << std::endl;
// add to database
}
model.h
#include <map>
#include<string>
#include <vector>
using std::string;
class Model {
private:
std::map<string, string> data;
string table;
public:
Model(const string table);
void addVal(const string& key, const string& val);
};
model.cpp
#include "model.h"
#include <string>
Model::Model(const string table) {
this->table = table;
}
void Model::addVal(const string& key, const string& val) {
(data)[key] = val;
}