I'm getting a weird problem in memory deallocation.
I have the following code for class MemoryPartition:
#include <cstring>
#include <iostream>
#include "memorypartition.h"
MemoryPartition::MemoryPartition(int maxSize) {
this->partitionArray = new char[maxSize];
memset(this->partitionArray, ((int) '$'), maxSize);
this->maxSize = maxSize;
this->isFree = true;
}
MemoryPartition::~MemoryPartition() {
delete[] this->partitionArray;
this->partitionArray = NULL;
maxSize = 0;
}
void MemoryPartition::setFree(bool isFree) {
this->isFree = isFree;
}
bool MemoryPartition::getFree() {
return this->isFree;
}
int MemoryPartition::getMaxSize() {
return this->maxSize;
}
void MemoryPartition::getPartitionArray() {
for(int i = 0;i < maxSize;i++) {
std::cout << partitionArray[i] << ' ';
}
std::cout << std::endl;
}
and the following code for MemoryManager:
#include "memorymanager.h"
#include <iostream>
#include <cstdlib>
MemoryManager::MemoryManager() {
}
MemoryManager::~MemoryManager() {
memory.clear();
}
void MemoryManager::defmem(int bytes) {
MemoryPartition *memPartition;
int maxMemorySize = bytes;
while(maxMemorySize != 0) {
int partitionSize = this->randomPartitionSize(maxMemorySize);
memPartition = new MemoryPartition(partitionSize);
this->memory.push_back(*memPartition);
std::cout << memPartition->getMaxSize() << std::endl;
memPartition->getPartitionArray();
maxMemorySize -= partitionSize;
delete memPartition;
memPartition = NULL;
}
}
int MemoryManager::randomPartitionSize(int maxSize) {
int value;
srand(time(NULL));
value = (rand() % maxSize) + 1;
return value;
}
and I'm getting a weird at delete[] in MemoryPartition destructor. Valgrind is telling me there are 13 frees and 10 allocs, but I can't see a reason why this delete[] would be called 3x.
Anyone see the problem I couldn't figure out?
Thanks in advance.
[]'s,
Its impossible to tell from the code above.
But my guess is that you need to define the copy constructor and assignment operator.
See Rule of 4 (Google/Wiki it).
Try the following:
class MemoryPartition
{
// Just add these two lines (keep them private)
MemoryPartition(MemoryPartition const&); // Don't define.
MemoryPartition& operator=(MemoryPartition const&); // Don't define.
<CLASS STUFF AS BEFORE>
};
Compile the code now. If it fails because the above are private then you have accidentally made a copy of the object somewhere and are doing a double delete on the pointer.
Related
I have seen similar questions but cannot solve in my
#include <iostream>
#include <list>
class Mohican {
protected:
int Id;
static int lastId;
static std::list<Mohican*> lastMohicans;
public:
Mohican() {
lastId += 1;
Id = lastId;
lastMohicans.push_back(this);
}
~Mohican() {
lastId -= 1;
lastMohicans.push_back() // smth instead of push_back;
}
static Mohican getLastMohican() {
return *lastMohicans.back();
}
int getId() {
return Id;
}
};
std::list<Mohican*> Mohican::lastMohicans;
int Mohican::lastId = 0;
int main() {
Mohican* first = new Mohican();
Mohican* second = new Mohican();
Mohican* third = new Mohican();
std::cout << Mohican::getLastMohican().getId() << std::endl;
delete third;
std::cout << Mohican::getLastMohican().getId() << std::endl;
}
I return after his Mohican, but I also have the right to delete any Mohican, the destructor does not work correctly, it only deletes the last one, but I need to delete the one I entered. How can this be implemented?
I'm getting Segmentation Fault error. I'm fairly new to C++ so not really familiar with pointers and other such things. This seems to be a fundamental aspect but i can't seem to figure it out, I've spent countless hours on it.
I have 5 files element.h, element.cpp, heap.h, heap.cpp, main.cpp
error occurs on the line
h.setElements(e,i);
Which is a function in Heap.cpp
I know it has something to do with arrays
MAIN.CPP
#include <iostream>
#include <stdio.h>
#include <stdlib.h>
#include "heap.h"
#include "element.h"
using namespace std;
int main(){
Heap h;
h = h.initialize(3);
for(int i=0;i<h.getCapacity(); ++i){
Element e;
e.setKey(i);
h.setElements(e,i); // Error occurs here
}
h.printHeap(h);
return 0;
}
HEAP.H
#ifndef heap_h
#define heap_h
#include "element.h"
#include <iostream>
using namespace std;
class Heap {
public:
Element* getElements();
void setElements(Element e,int index);
Heap initialize(int n);
void printHeap(Heap heap);
private:
int capacity;
int size;
Element* H;
};
#endif
HEAP.CPP
#include "heap.h"
Heap Heap::initialize(int n){
H = new Element[n];
Heap h;
h.capacity = n;
h.size = 0;
return h;
}
void Heap::printHeap(Heap heap){
for(int i=0;i<heap.capacity;++i){
cout << "Element " << i << " = " << H[i].getKey() << endl;
}
}
void Heap::setCapacity(int nCapacity ) {
capacity = nCapacity;
}
int Heap::getCapacity(void) {
return capacity;
}
void Heap::setSize(int nSize ) {
size = nSize;
}
int Heap::getSize(void) {
return size;
}
Element* Heap::getElements(void){
return H;
}
void Heap::setElements(Element e,int index){
H[index] = e;
}
You are getting the error because H is null.
The mistake is in the Heap::initialize(Element, int) method.
You are assigning the local variable H of the Heap object you are calling the method in, instead of the object you are returning.
Heap Heap::initialize(int n){
H = new Element[n]; // You are assigning H for the current heap object
Heap h; // Here you are creating a new Heap object
h.capacity = n;
h.size = 0;
return h; // You haven't assigned h.H
}
Why are you creating a new Heap object and returning it?
You can make the initialize method a void, like this:
void Heap::initialize(int n) {
H = new Element[n];
capacity = n;
size = 0;
}
Or if you need to return a new Heap object you can do it like this:
Heap Heap::initialize(int n) {
Heap h;
h.H = new Element[n];
h.capacity = n;
h.size = 0;
return h; // You have assigned h.H
}
Hope this was helpful.
I'm trying to dust off my C++. I knocked together a simple program to find the Fibonacci sequence with memoization. There's a memory leak, and I can't seem to figure out why. The leak is reported in Fibonacci::setToFind.
Sorry for the long code chunk, but I couldn't figure out how to make a more minimal reproducible example.
#include <iostream>
class Fibonacci
{
public:
int m_valuefound;
int m_tofind;
long int *m_memo;
int findValue(int value){
if (m_memo[value] == 0) {
if (value == 0 || value == 1) {
m_memo[value] = 1;
} else {
m_memo[value] = findValue(value-1) + findValue(value-2);
}
}
return m_memo[value];
}
void setToFind(int value){
m_tofind = value;
m_memo = new long int[value];
std::fill_n(m_memo,value,0);
}
void solve(){
int value = m_tofind;
int result = findValue(value);
std::cout<< "Value is: " << result << std::endl;
}
~Fibonacci(){};
};
int main (int argc, char * const argv[]) {
std::cout << "Enter integer values until you'd like to quit. Enter 0 to quit:";
int user_ind=0;
// for testing non-interactivly
while(true){
for (user_ind=1; user_ind<45; user_ind++) {
Fibonacci *test = new Fibonacci;
test->setToFind(user_ind);
test->solve();
delete test;
}
}
return 0;
}
You never delete m_memo in the destructor of Fibonacci.
Since you're allocating m_memo as an array, you should delete with delete[] m_memo
Here is working code with a non-copyable Fibonacci class. Why don't
you allocate the memory in the constructor. Use RAII wherever possible
and remember The Rule of Five. Avoid all of this in the first place by
using std::vector.
#include <iostream>
class Fibonacci
{
public:
int m_valuefound;
int m_tofind;
long int *m_memo;
int findValue(int value){
if (m_memo[value] == 0) {
if (value == 0 || value == 1) {
m_memo[value] = 1;
} else {
m_memo[value] = findValue(value-1) + findValue(value-2);
}
}
return m_memo[value];
}
void setToFind(int value){
m_tofind = value;
m_memo = new long int[value];
std::fill_n(m_memo,value,0);
}
void solve(){
int value = m_tofind;
int result = findValue(value);
std::cout<< "Value is: " << result << std::endl;
}
// why don't you allocate in the constructor?
Fibonacci() : m_valuefound(0), m_tofind(0), m_memo(nullptr) {}
~Fibonacci() {
delete[] m_memo;
};
// make the class non-copyable
Fibonacci(const Fibonacci&) = delete;
const Fibonacci& operator=(const Fibonacci&) = delete;
/*
C++03 non-copyable emulation
private:
Fibonacci(const Fibonacci&);
const Fibonacci& operator=(const Fibonacci&);
*/
};
You are allocating m_memo in setToFind:
m_memo = new long int[value];
but your destructor does not have a delete [] m_memo. You should initialize m_memo in your constructor and make you class non-copyable by disabling your copy constructor and assignment operator using delete if using C++11:
Fibonacci(const Fibonacci&) = delete;
const Fibonacci& operator=(const Fibonacci&) = delete;
Otherwise you can make them private. If you used a container such as std::vector your life would be much simpler.
I suggest you use more the STL algorithms. Here's a code snippet with a rather not optimized functor but you can get the idea of the power of the STL:
#include <vector>
#include <algorithm>
#include <iostream>
using namespace std;
class Fibonacci
{
public:
Fibonacci();
~Fibonacci() {}
int operator()();
private:
int n0_;
int n1_;
int n_;
};
Fibonacci::Fibonacci():n0_(0),n1_(1),n_(0)
{
}
int Fibonacci::operator()()
{
if(n_ > 1)
return (++n0_) + (++n1_);
else
return ++n_;
}
using namespace std;
int main()
{
Fibonacci func;
vector<int> v;
//generate 100 elements
generate_n(v.begin(),100,func);
//printing the values using a lambda expression
for_each(v.begin(),v.end(),[](const int val){cout << val << endl;});
return 0;
}
You can then apply the finding algorithm you want on the vector using find_if and defining your own functor.
#include <iostream>
#include <cstdlib>
#include <ctime>
#include <algorithm>
#include <vector>
using namespace std;
struct delete_ptr
{
template<typename T>
void operator()(T*& t)
{
delete t;
t = 0;
}
};
struct is_null_ptr
{
template<typename T>
bool operator()(T*& t)
{
return t == 0;
}
};
struct A
{
static void removeDead(A*& a)
{
if(a and a->dead)
delete_ptr()(a);
}
static void killSome(A* a)
{
if(a and a->isDead() == false and rand()%100 == 0)
{
static int counter = 0;
cout << "Kill___" << ++counter << endl;
a->kill();
}
}
static void reviveSome(A* a)
{
if(a and a->isDead() and rand()%3 == 0)
{
static int counter = 0;
cout << "Revive___" << ++counter << endl;
a->revive();
}
}
A():dead(false)
{
}
virtual ~A()
{
static int counter = 0;
cout << "Dtor___" << ++counter << endl;
}
bool isDead(){return dead;}
void kill(){dead = true;}
void revive(){dead = false;}
bool dead;
};
int main()
{
srand(time(0));
vector<A*> as;
for(int i = 0; i < 200; ++i)
{
A* a = new A;
as.push_back(a);
}
for_each(as.begin(),as.end(),A::killSome);
for_each(as.begin(),as.end(),A::reviveSome);
for_each(as.begin(),as.end(),A::removeDead);
as.erase( std::remove_if(as.begin(),as.end(),is_null_ptr()),as.end());
cout << as.size() << endl;
for_each(as.begin(),as.end(),delete_ptr());
as.clear();
return 0;
}
It allocates them, and prints the right output but I'm not sure this is the right thing I'm doing. I was just trying to use pointers in a vector and delete them when a certain condition happens, without using boost or c++11.
So what do you think about it?
Since the only smart pointer present in the current STL (auto_ptr) cannot be used in containers, I would say your way is a good one under the given conditions.
You could think about implementing your own unique_ptr or shared_ptr however.
PS: There are many reasons to use pointers instead of the actual objects in a container, one is polymorphism. Another one is that the actual objects are already stored somewhere else (think of an index structure to already stored objects).
I want to know is there something wrong in passing in passing vector reference to a function as in the example below. This code is running well and nice. But the same type of code in my project gives me crash. I don't know why.
In that case whenever I calls the function which need std::vector & . then in the called function the size of the vector reaches some millionsss.... I have attached screenshot where I am actually getting this crash.
I just wants to know is there something wrong in these type of implementations...
#include <iostream>
#include <vector>
#include <string>
class A {
public:
A() {}
~A() {}
void GetVector(std::vector<std::wstring> &in) {
std::wstring s = L"Hello";
for(int i = 0; i < 10; i++)
in.push_back(s);
}
};
class B {
public:
B() {}
~B() {}
void GetData() {
A a;
std::vector<std::wstring> s;
a.GetVector(s);
}
};
int main() {
B b;
b.GetData();
return 0;
}
Real code where I am getting the crash...
void SCPreferenceComp::PopulateComboBox()
{
SCConfig *config = SCConfig::GetInstance();
std::vector<std::wstring> languages;
config->GetAllLangugesName(languages);
for(size_t i = 0; i != languages.size(); i++)
mLangListComboBox->addItem(languages[i].c_str(), i+1);
if(mLangListComboBox->getNumItems() > 0)
mLangListComboBox->setSelectedId(1);
}
bool SCConfig::GetAllLangugesName(std::vector<std::wstring> &outLangNames)
{
bool retVal = false;
do
{
if(!mXMLDoc)
break;
xercesc::DOMNodeList *langNodeList = mXMLDoc->getElementsByTagName(strToX("language"));
if(!langNodeList)
break;
const XMLSize_t langCount = langNodeList->getLength();
for(XMLSize_t i = 0; i < langCount; i++)
{
xercesc::DOMNode *curLangNode = langNodeList->item(i);
if(!curLangNode)
continue;
xercesc::DOMElement *curLangElem = dynamic_cast<xercesc::DOMElement*>(curLangNode);
if(!curLangElem)
continue;
wxString s = strToW(curLangElem->getAttribute(strToX("name")));
outLangNames.push_back(s.c_str());
}
retVal = true;
}while(false);
return retVal;
}
I can't see anything wrong in that implementation other than the fact that it doesn't have any visible end result which leads me to believe it may not exactly match your failing code.