Memory Leakage while using dynamic array pointer in C++ - c++

As the title reads, I get memory leakage when I run my program. However, I think the problem is that I do not tell the destructor to free all of the memory when the program is done. But the problem is that the program crashes when I try to put my freeMemory() function in the destructor. The compiler says that the function getString() in my base class could not read from string. I wonder if you can see the problem, because I surely can not... And to not get too many rows of code, I will only post the functions which could be the possible source of leakage. Handler.h:
class Handler {
private:
Competitor* *person;
int capacity;
int nrOfCompetitors;
void expand();
void initiate(int start) const;
int find(string name) const;
void freeMemory();
public:
Handler(int capacity = 3);
Handler(const Handler & origObj);
virtual ~Handler();
Handler operator=(const Handler & origObj);
bool addExerciser(string name, string gender, int age);
bool addProffs(string name, string gender, string compound, int nrOfSeasons);
void getCompetitors(string arr[]) const;
int getNrOfCompetitors() const;
void getProffs(string arr[]) const;
int getNrOfProffs() const;
void getExercisers(string arr[]) const;
int getNrOfExercisers() const;
bool removeCompetitor(string name);
bool changeNrOfSeasons(string name, int newNrOfSeasons) const;
void sortCompetitors();
};
Handler.cpp (just the relevant functions):
void Handler::expand() {
this->capacity += 5;
Competitor* *tmp = new Competitor*[capacity];
for (int i = 0; i < this->nrOfCompetitors; i++) {
tmp[i] = this->person[i];
}
delete[] this->person;
this->person = tmp;
this->initiate(nrOfCompetitors);
}
void Handler::initiate(int start) const {
for (int i = start; i < this->capacity; i++) {
person[i] = nullptr;
}
}
void Handler::freeMemory() {
for (int i = 0; i < nrOfCompetitors; i++) {
delete person[i];
}
delete[] person;
}
Handler::Handler(int capacity) {
this->capacity = capacity;
this->nrOfCompetitors = 0;
this->person = new Competitor*[this->capacity];
initiate(0);
}
Handler::Handler(const Handler & origObj) {
this->capacity = origObj.capacity;
this->nrOfCompetitors = origObj.nrOfCompetitors;
this->person = new Competitor*[origObj.capacity];
for (int i = 0; i < this->capacity; i++) {
person[i] = origObj.person[i];
}
initiate(nrOfCompetitors);
}
Handler::~Handler() {
//freeMemory();
delete[] person;
}
Handler Handler::operator=(const Handler & origObj) {
if (this != &origObj) {
freeMemory();
this->capacity = origObj.capacity;
this->nrOfCompetitors = origObj.nrOfCompetitors;
this->person = new Competitor*[origObj.capacity];
for (int i = 0; i < this->capacity; i++) {
person[i] = origObj.person[i];
}
initiate(nrOfCompetitors);
}
return *this;
}
bool Handler::removeCompetitor(string name) {
bool removed = false;
int found = find(name);
if (found != -1) {
delete person[found];
for (int i = found; i < nrOfCompetitors; i++) {
person[found] = person[found + 1];
}
delete person[nrOfCompetitors];
nrOfCompetitors -= 1;
removed = true;
}
return removed;
}
void Handler::sortCompetitors() {
Competitor* tmp;
bool swap;
do {
swap = false;
for (int i = 0; i < nrOfCompetitors - 1; i++) {
if (person[i]->getName() > person[i + 1]->getName()) {
tmp = person[i];
person[i] = person[i + 1];
person[i + 1] = tmp;
swap = true;
}
}
} while (swap);
}
EDIT:
When the program crashes while I am trying to use the freeMemory() function in my destructor, the compiler says that the getString() function in my base class could not read character from string.
Competitor.h (base class):
string getString() const;
virtual string getSpecificString() const = 0;
Competitor.cpp:
string Deltagare::getString() const {
return "Name: " + this->name + "\nGender: " + this->gender + "\n" + this->getSpecificString();
}
Exerciser.h (sub class):
virtual string getSpecificString() const;
Exerciser.cpp
string Exerciser::getSpecificString() const {
return "Age: " + to_string(this->age);
}
Solved! Solution:
The problems were in the destructor, assignment operator and the copy-constructor, but they are fixed now. I used a clone method because I was not able to type person[i] = new Competitor[origObj.person[i]] because of the fact that the Competitor class is an abstract class.
Competitor.h:
virtual Competitor* clone() const = 0;
Exerciser.h:
Exerciser* clone() const;
Exerciser.cpp:
Exerciser * Exerciser::clone() const {
return new Exerciser(*this);
}
Edit in the copy-constructor and the assignment operator:
this->person = new Competitor*[origObj.capacity];
for (int i = 0; i < origObj.nrOfCompetitors; i++) {
person[i] = origObj.person[i]->clone();
}
Edit in the destructor:
Handler::~Handler() {
freeMemory();
}

Related

Still having an Unhandled Exception after editing it a bit

Inventory::Inventory()
{
this->cap = 10;
this->nrOfItems = 0;
this->itemArr = new Item* [cap]();
}
Inventory::~Inventory()
{
for (size_t i = 0; i < this->nrOfItems; i++)
{
delete this->itemArr[i];
}
delete[] this->itemArr;
}
void Inventory::expand()
{
this->cap *= 2;
Item **tempArr = new Item*[this->cap]();
for (size_t i = 0; i < this->nrOfItems, i++;)
{
tempArr[i] = new Item(*this->itemArr[i]);
}
for (size_t i = 0; i < this->nrOfItems, i++;)
{
delete this->itemArr[i];
}
delete[] this->itemArr;
this->itemArr = tempArr;
this->initialize(this->nrOfItems);
}
void Inventory::initialize(const int from)
{
for (size_t i = from; i < cap, i++;)
{
this->itemArr[i] = nullptr;
}
}
void Inventory::addItem(const Item& item)
{
if (this->nrOfItems >= this->cap)
{
expand();
}
this->itemArr[this->nrOfItems++] = new Item(item);
}
void Inventory::removeItem(int index)
{
}
Above is my code from Inventory.cpp and the issue is that I keep getting an Unhandled Exception from the line that has:
this->itemArr[i] = nullptr;
I have no idea where I'm messing up in the code. Below I am posting from Inventory.h:
class Inventory
{
private:
int cap;
int nrOfItems;
Item **itemArr;
void expand();
void initialize(const int from);
public:
Inventory();
~Inventory();
void addItem(const Item &item);
void removeItem(int index);
inline void debugPrint() const
{
for (size_t i = 0; i < this->nrOfItems; i++)
{
std::cout << this->itemArr[i]->debugPrint() << std::endl;
}
}
};
This is where itemArr should be housed but for some reason, it is not pulling. I am new to coding so I don't know all of the tips and tricks involved with it.
In the loop i < cap, i++;, you will first check if i is in bounds, and then increase it by one before the loop body executes. Thus if i=cap-1 the check will pass, i will become cap and you're out of bounds.
Instead write (size_t i = from; i < cap;i++), so that the increment of i is executed after the loop body.
A see several problems with your code:
In Inventory::expand(), since you are working with an array of pointers (why not an array of objects?), there is no need to make clones of the existing Item objects to the new array, just copy the existing pointers as-is. You are just expanding the array to fit more pointers, so the clones are wasted overhead. Not a fatal issue, but it is something you should be aware of.
In both Inventory::initialize() and Inventory::expand(), your loops are setup incorrectly. You are performing the i++ in the wrong place. Given this definition of a loop:
for ( <init-statement> <condition> ; <iteration_expression> )
You are performing the i++ as part of the <condition>, not the <iteration_expression>. A simply typo caused by you using the comma operator instead of ;, but an important typo nonetheless.
Inventory is violating the Rule of 3/5/0, by not implementing copy/move constructors and copy.move assignment operators.
With that said, try this instead:
class Inventory
{
private:
size_t cap;
size_t nrOfItems;
Item **itemArr;
void expand();
public:
Inventory();
Inventory(const Inventory &src);
Inventory(Inventory &&src);
~Inventory();
Inventory& operator=(Inventory rhs);
void addItem(const Item &item);
void removeItem(size_t index);
inline void debugPrint() const
{
for (size_t i = 0; i < nrOfItems; ++i)
{
std::cout << itemArr[i]->debugPrint() << std::endl;
}
}
};
Inventory::Inventory()
{
cap = 10;
nrOfItems = 0;
itemArr = new Item*[cap]();
}
Inventory::Inventory(const Inventory &src)
{
cap = src.cap;
nrOfItems = src.nrOfItems;
itemArr = new Item*[cap]();
for(size_t i = 0; i < nrOfItems; ++i)
{
itemArr[i] = new Item(*(src.itemArr[i]));
}
}
Inventory::Inventory(Inventory &&src)
{
cap = src.cap; src.cap = 0;
nrOfItems = src.nrOfItems; src.nrOfItems = 0;
itemArr = src.itemArr; src.itemArr = nullptr;
}
Inventory::~Inventory()
{
for (size_t i = 0; i < nrOfItems; ++i)
{
delete itemArr[i];
}
delete[] itemArr;
}
Inventory& Inventory::operator=(Inventory rhs)
{
Inventory temp(std::move(rhs));
std::swap(cap, temp.cap);
std::swap(nrOfItems, temp.nrOfItems);
std::swap(itemArr, temp.itemArr);
return *this;
}
void Inventory::expand()
{
size_t newCap = cap * 2;
Item **tempArr = new Item*[newCap]();
for (size_t i = 0; i < nrOfItems; ++i)
{
tempArr[i] = itemArr[i];
}
delete[] itemArr;
itemArr = tempArr;
cap = newCap;
}
void Inventory::addItem(const Item& item)
{
if (nrOfItems >= cap)
{
expand();
}
itemArr[nrOfItems] = new Item(item);
++nrOfItems;
}
void Inventory::removeItem(size_t index)
{
if (index < nrOfItems)
{
Item *item = itemArr[index];
for(size_t i = index + 1; i < nrOfItems; ++i)
{
itemArr[i-1] = itemArr[i];
}
--nrOfItems;
itemArr[nrOfItems] = nullptr;
delete item;
}
}
That being said, you really should be using std::vector instead, let it handle these details for you, eg:
#include <vector>
class Inventory
{
private:
std::vector<Item> itemVec;
public:
Inventory();
void addItem(const Item &item);
void removeItem(size_t index);
inline void debugPrint() const
{
for (Item &item : items)
{
std::cout << item.debugPrint() << std::endl;
}
}
};
Inventory::Inventory()
{
itemVec.reserve(10);
}
void Inventory::addItem(const Item& item)
{
itemVec.emplace_back(item);
}
void Inventory::removeItem(size_t index)
{
if (index < itemVec.size())
{
itemVec.erase(itemVec.begin() + index);
}
}
See how much simpler that is? :)

How to convert template T to a class pointer

I am trying to implement a template Array class that can hold pointers as well as primitive data types.
But when calling the destructor, the pointers in that array are not properly deleting.
So I am trying to convert each item in that array to its corresponding class and call delete. But I met with an issue. I'm not able to convert T type to my class pointer.
My intention is to delete items in that array. Can someone please help in this?
template <class T>
class LIBRARY_EXPORT MyArrayT
{
public:
MyArrayT()
{
this->count = 0;
}
~MyArrayT()
{
if ((this->count) > 0)
{
//std::cout << "Deleting Array values" << std::endl;
delete[] this->values;
//free(this->values);
/*for (int i = 0; i < this->count; i++)
{
delete this->values[i];
}*/
this->count = 0;
}
}
void SetValue(std::vector< T > items)
{
//Delete existing memory
delete[] this->values;
this->count = items.size();
if (this->count > 0)
{
this->values = new T[this->count];
for (int i = 0; i < count; i++)
{
this->values[i] = items[i];
}
}
}
void SetValue(T items, int index)
{
if (this->count > index)
{
this->values[index] = items;
}
}
T GetValue(int index)
{
if (this->count > index)
{
return this->values[index];
}
return NULL;
}
T* GetValue()
{
return this->values;
}
_int64 GetCount()
{
return this->count;
}
private:
_int64 count;
T* values;
};
class LIBRARY_EXPORT MyString
{
public:
MyString();
~MyString();
void SetValue(std::string str);
std::string GetValue();
_int64 GetCount();
private:
_int64 count;
char* value;
};
int main()
{
MyArrayT<MyString*>* MyArrayValue = new MyArrayT<MyString*>() ;
vector<MyString*> value9;
MyString* opt1 = new MyString();
opt1->SetValue("Option: 1");
value9.push_back(opt1);
MyArrayValue->SetValue(value9);
MyArrayT<int>* MyArrayValueInt = new MyArrayT<int>() ;
vector<int> value1;
value1.push_back(1);
value1.push_back(2);
MyArrayValueInt->SetValue(value1);
delete MyArrayValue; //Calling this delete doesn't calling the ~MyString() destructor
delete MyArrayValueInt;
}

How to overload operator + in c++ to be able whrite c_str = "smth" + c_str;

I would like to make a CMyString class. It represents an object with contains char array. I need to overload opereators to be able to sum these objects. Here is this class
CMyString::CMyString()
{
i_length = 0;
n_string = new char[1];
n_string[0] = '\0';
}
CMyString::CMyString(const char *cChar)
{
i_length = iSourceLength(cChar);
n_string = new char[i_length];
for (int ii = 0; ii < i_length; ii++)
n_string[ii] = cChar[ii];
}
CMyString::CMyString(const CMyString &pcOther)
{
i_length = pcOther.i_length;
n_string = new char[i_length];
for (int ii = 0; ii < i_length; ii++)
n_string[ii] = pcOther.n_string[ii];
}
void CMyString::vCopyFrom(const CMyString &pcOther)
{
for (int ii = 0; ii < i_length; ii++)
n_string[ii] = pcOther.n_string[ii];
}
bool CMyString::bResize(int newSize)
{
if (newSize <= 0)
return false;
delete(this->n_string);
this->n_string = new char[newSize];
i_length = newSize;
return true;
}
//bool CMyString::bResize(int newSize)
int CMyString::iSourceLength(const char *cChar)
{
int i_source_length = 0;
while (cChar[i_source_length] != '\0')
i_source_length++;
return i_source_length;
}
//int CMyString::iSourceLength(const char *cChar)
CMyString& CMyString:: operator= (const CMyString& pcOther)
{
if (this != &pcOther) // guard against a = a;
{
delete[] n_string; // release old memory & then allocate new memory
i_length = pcOther.i_length;
n_string = new char[i_length];
vCopyFrom(pcOther);
}
return *this; // return a reference to itself to allow a = b = c;
}
//CMyString& CMyString:: operator= (const CMyString& pcOther)
void CMyString:: operator= (const char *cChar)
{
if (i_length != 0)
delete[] n_string;
i_length = iSourceLength(cChar); // count the length of init value
n_string = new char[i_length]; // allocate storage
for (int ii = 0; ii < i_length; ii++) // copy init value into storage
n_string[ii] = cChar[ii];
}
//void CMyString:: operator= (const char *cChar)
CMyString& CMyString:: operator+ (const CMyString& pcOther)
{
CMyString *c_res = new CMyString;
if (i_length == 0 && pcOther.i_length == 0)
{
c_res->i_length = 0;
c_res->n_string = NULL;
}
c_res->i_length = i_length + pcOther.i_length;
c_res->n_string = new char[c_res->i_length];
int ii;
for (ii = 0; ii < i_length; ii++)
c_res->n_string[ii] = n_string[ii];
for (int ij = 0; ij < pcOther.i_length; ij++, ii++)
c_res->n_string[ii] = pcOther.n_string[ij];
return *c_res;
}
CMyString::operator char*()
{
return n_string;
}
//CMyString& CMyString:: operator+ (const CMyString& pcOther)
CMyString::operator char*() const
{
return n_string;
}
What should i do to be able to write c_str = "smth" + c_str?? Compiler underlines me this plus. No operator "+" matches this operands. Operands types are: const char[4] and CMyString?
For more information you can visit this website.
class CMyString
{
private:
string str;
public:
CMyString(string _str) { str = _str; }
friend CMyString operator+(string value, CMyString Str);
string GetStr() {return str;};
};
CMyString operator+(string value, CMyString Str)
{
return CMyString(value + Str.str);
}
int main()
{
CMyString test("Test");
test = "smth" + test;
cout << test.GetStr();
return 0;
}

Trying to write my own string class getting exception in gcc

Basically what the title says. I have been trying to write my own string class using only char arrays and, while my code works when I run it in Visual Studio, I have trouble with it when using gcc .The problem seems to be coming when i try to delete in my getData function(can be seen below) The exception I get is:
Exception thrown at 0x6262436B (ucrtbased.dll) in string.exe: 0xC0000005: Access violation reading location 0xCCCCCCBC. occurred
My code :
Header:
#pragma warning(disable:4996)
#ifndef STRING_STRING_H
#define STRING_STRING_H
#include<iostream>
#include<cstring>
#include<fstream>
class String {
private:
char *data; //holds the text
size_t maxSize; //maximum number of chars in data
size_t currentSize; //current number of chars in data
void getData(const char *, size_t maxSize); //sets currentSize to the other char* size and
// copies the content of the other char* to data
public:
String(); //default constructor
~String(); //destructor
String(const String &); //copy-constructor(from String)
String(const char *); //copy-constructor(from char*)
String operator=(const String &); //operator= (from string)
String operator=(const char *); //operator=(from char*)
size_t length() const; //currentSize getter
void addChar(const char); //adds a char to the data array
void getLine(std::ifstream&,const char); // reads line till deliminator and stores it in this string object(all data previously stored is lost)
size_t find(const char*); //searches for text in the string and if found returns the starting position , if not found returns -1;
void print() const; //prints the string object to console
char* toChar() const; //returns a new allocated char pointer with the text inside (must be deleted afterwards)
};
#endif //STRING_STRING_H
cpp:
#include "String.h"
String::String() {
currentSize = 0;
maxSize = 16;
try {
data = new char[maxSize];
data[0] = '\0';
}
catch (std::bad_alloc &) {
std::cerr << "Not enough memory" << std::endl;
throw;
}
}
String::~String() {
delete[] data;
}
size_t String::length() const {
return currentSize;
}
String::String(const String &other) {
this->maxSize = other.maxSize;
getData(other.data, maxSize);
}
String::String(const char *other) {
this->maxSize = strlen(other) *2;
getData(other, maxSize);
}
void String::getData(const char *dataSource, size_t maxSize) {
currentSize = strlen(dataSource);
try {
char *newData = new char[maxSize];
delete[] data;
data = newData;
strcpy(data, dataSource);
}
catch (std::bad_alloc &) {
std::cerr << "Not enough memory" << std::endl;
throw;
}
}
String String::operator=(const String &other) {
if (this != &other) {
maxSize = other.maxSize;
getData(other.data, maxSize);
}
return *this;
}
String String::operator=(const char *other) {
if (this->data != other) {
maxSize = strlen(other) *2;
getData(other, maxSize);
}
return *this;
}
void String::addChar(const char newChar) {
if (maxSize == currentSize+1) {
maxSize *= 2;
getData(this->data, maxSize);
}
data[currentSize++] = newChar;
}
void String::getLine(std::ifstream & is, const char delim='\n')
{
char temp;
while (!is.eof())
{
is.get(temp);
if (temp == delim)
break;
else
addChar(temp);
}
return;
}
size_t String::find(const char * text)
{
size_t currPos=-1;
bool found = 0;
for (size_t i = 0; i < currentSize; i++)
{
if (data[i] == text[0])
{
for (size_t j = i+1; j < currentSize; j++)
{
if (data[j] == text[j - i])
found = 1;
else
{
found = 0;
break;
}
}
if (found == 1)
{
currPos = i;
break;
}
}
}
return currPos;
}
void String::print() const
{
for (size_t i = 0; i < currentSize; i++)
{
std::cout << data[i];
}
std::cout << std::endl;
}
char * String::toChar() const
{
char* text= new char[currentSize+1];
for (size_t i = 0; i < currentSize; i++)
{
text[i] = data[i];
}
text[currentSize + 1] = 0;
return text;
}
Your problem is caused by calling delete [] on uninitialized memory.
In the copy constructor, the data member is not initialized before calling getData(). In getData(), you are using delete [] data;.
You could initialize data to nullptr in the constructors to avoid the problem.
It's always a good idea to initialize all variables to some sensible value before the body of the constructor. E.g. you can implement the copy constructor as:
String::String(const String &other) : currentSize(0),
maxSize(other.maxSize),
data(nullptr)
{
getData(other.data, maxSize);
}
Similarly, implement the constructor from char const* as:
String::String(const char *other) : currentSize(0),
maxSize(strlen(other) *2),
data(nullptr)
{
getData(other, maxSize);
}

Function removes too much

I'm doing a phone registry and in it you need to be able to add, remove and show the phones on stock. I've made it possible to add in phones but whenever I add let's say 3 phones and remove the second one then both the third and second phone are deleted and I don't understand why.
This is my CellPhoneHandler.h file:
#ifndef CELLPHONEHANDLER_H
#define CELLPHONEHANDLER_H
#include "CellPhone.h"
class CellPhoneHandler
{
private:
CellPhone **phone;
int nrOfPhones;
int priceOfPhone;
int stockCapacity;
int nrOfPhonesInArr;
public:
CellPhoneHandler();
~CellPhoneHandler();
void addPhone(string brand, int nrOf, int price);
bool removePhoneFromStock(string name, int nrOf);
int getNrOfPhones() const;
int getNrOfPhonesInArr() const;
int getPrice() const;
void getPhonesAsString(string arr[], int nrOf, int priceOfPhone) const;
};
#endif // !CELLPHONEHANDLER_H
this is my CellPhoneHandler.cpp file.
#include "CellPhoneHandler.h"
CellPhoneHandler::CellPhoneHandler()
{
this->phone = nullptr;
this->nrOfPhones = 0;
this->priceOfPhone = 0;
this->stockCapacity = 0;
this->nrOfPhonesInArr = 0;
}
CellPhoneHandler::~CellPhoneHandler()
{
for (int i = 0; i < nrOfPhonesInArr; i++)
{
delete phone[i];
}
delete[] phone;
}
void CellPhoneHandler::addPhone(string brand, int nrOf, int price)
{
if (stockCapacity < nrOfPhonesInArr + 1)
{
CellPhone ** tempArray = new CellPhone*[this->nrOfPhonesInArr + 1];
for (int i = 0; i < nrOfPhonesInArr; i++)
{
tempArray[i] = this->phone[i];
}
delete[] this->phone;
this->phone = tempArray;
this->phone[this->nrOfPhonesInArr] = new CellPhone(brand, nrOf, price);
this->nrOfPhonesInArr++;
//this->stockCapacity++;
}
}
bool CellPhoneHandler::removePhoneFromStock(string name, int nrOf)
{
bool phoneFound = false;
int index = nrOfPhonesInArr;
for (int i = 0; i < nrOfPhonesInArr; i++)
{
if (this->phone[i]->getBrand() == name);
{
index = i;
phoneFound = true;
this->nrOfPhonesInArr--;
}
}
if (phoneFound == true)
{
delete phone[index];
phone[index] = nullptr;
}
return phoneFound;
}
int CellPhoneHandler::getNrOfPhones() const
{
return this->nrOfPhones;
}
int CellPhoneHandler::getNrOfPhonesInArr() const
{
return this->nrOfPhonesInArr;
}
int CellPhoneHandler::getPrice() const
{
return this->priceOfPhone;
}
void CellPhoneHandler::getPhonesAsString(string arr[], int nrOf, int priceOfPhone) const
{
for (int i = 0; i < nrOf; i++)
{
arr[i] = this->phone[i]->toString();
}
}
The problem is caused by an unwanted ;.
if (this->phone[i]->getBrand() == name); // if ends here.
The next block is executed for all items.
{
index = i;
phoneFound = true;
this->nrOfPhonesInArr--;
}
Remove that ; in the if line.