Memory leak with lists c++ - c++

The idea of the function is to divide the original list in X Lists all gather in a single array without delete nor creating new Cells.
The function do his job great but when I check the leaks with valgrind or Dr. Memory, It appears to have some leak problems...
List* function (List & todivide, int t = 2){
Cell* aux = todivide.l; // l is the head of the list
int tam = (todivide.size()/t == 0) ? todivide.size()/t : todivide.size()/t+1;
List* arrayoflists = new List [tam];
for(int i = 0, k = 0; aux != 0; i++){
if(i%t == 0){
arrayoflists[k].l = aux;
aux = aux->sig;
k++;
}
if(i%t == t-1){
Cell* p = aux->sig;
aux->sig = 0;
aux = p;
}
}
l.l = 0;
return arrayoflists;
}
I see nothing wrong... Any ideas?
Thanks in advance

There's nothing wrong inside the function but since you're returning a pointer that you created using new, you might be forgetting to delete the returned pointer where ever you're using it outside the function.

Related

getting an error code about using uninitialized memory

I am using visual studio to code with, and I do not understand why i am getting the error "Error C6001 - Using uninitialized memory '*tempPtr' " at only the line right below the else if condition statement.
void removeNumber(double*& arrayPtr, double number, int& size) {
bool found = false;
double* tempPtr = new double[size-1];
for (int i = 0; i < size; i++) {
if (arrayPtr[i] == number) {
found = true;
}
else if (found == false && arrayPtr[i] != number) {
arrayPtr[i] = tempPtr[i];
}
else {
arrayPtr[i] = tempPtr[i - 1];
}
} delete[] arrayPtr;
arrayPtr = tempPtr;
--size;
}
arrayPtr[i] = tempPtr[i];
In this line, you try to assign an uninitialized tempPtr[i] to an initialized arrayPtr[i]. It should be the other way around. However, if what you want to do is to assign a null pointer to arrayPtr[i], you can initialize tempPtr with null pointers.
This is not related to the question but I notice at the end you de-allocate the memory for arrayPtr and then use arrayPtr. This will crash your program at run-time. You only want to de-allocate when you have no use for it anymore.

Trying to find two random nodes and swap them in a doubly linked list

This program is basically just suppose to shuffle a deck of cards. The cards are stored in a doubly linked list, so 52 nodes. I'm getting a read access error in the getNode function, but I'm pretty sure my loop is correct, so I think the error is stemming from somewhere else. Maybe the swap function. My first step is getting pointers to the nodes that I'm trying to swap.
So I made a function, and I'm pretty sure it's right, except I'm wondering if I should be returning *traverseP instead of just traverseP. I don't think so, because I want to return a pointer to the node, not the value inside the node.
template<class T>
typename ReorderableList<T>::Node *ReorderableList<T>::getNode(int i) const
{
int count = 0;
for (Node *traverseP = firstP; traverseP != NULL; traverseP = traverseP->nextP) {
if (count == i)
return traverseP;
count++;
}
return NULL;
}
Next I made a swap function that take two ints, they represent the values I'm passing into the getNode function
template<class T>
void ReorderableList<T>::swap(int i, int j)
{
// Get pointers to ith and jth nodes.
Node *iPtr = getNode(i);
Node *jPtr = getNode(j);
//create temp Node and store the pointers
Node *temp = new Node;
temp = iPtr->prevP;
temp = iPtr->nextP;
//adjust the iPtr next/prev pointers
iPtr->prevP = jPtr->prevP;
iPtr->nextP = jPtr->nextP;
//adjust the jPtr next/prev pointers
jPtr->prevP = temp->prevP;
jPtr->nextP = temp->prevP;
//I'm a little unclear on these lines. I think they're checking if
//iPtr and jPtr have null pointers. I've tried making them equal jPtr and
//iPtr and that strangly didn't make any difference.
if (iPtr->prevP)
iPtr->prevP->nextP = jPtr;
if (iPtr->nextP)
iPtr->nextP->prevP = jPtr;
if (jPtr->prevP)
jPtr->prevP->nextP = iPtr;
if (jPtr->nextP)
jPtr->nextP->prevP = iPtr;
delete temp;
}
This is the shuffle function where this whole shabang kicks off
template<class T>
void randomShuffle(ReorderableList<T> &list, int n)
{
int randNum = 0;
for (int i = n-1; i > 0; i--)
{
randNum = (rand() & (i + 1));
if (randNum > i)
std::swap(randNum, i);
list.swap(randNum, i);
}
}
I've checked a couple different resources for the swap function and found two that both claimed they were correct, but they looked different to me.
Resource 1
Resource 2

C++ memory leak, where?

I'm having a problem with the code attached below. Essentially it generates a huge memory leak but I can't see where it happens.
What the code does is receiving an array of strings, called prints, containing numbers (nodes) separated by ',' (ordered by desc number of nodes), finding other compatible prints (compatible means that the other string has no overlapping nodes 0 excluded because every print contains it) and when all nodes are covered it calculates a risk function on the basis of a weighted graph. In the end it retains the solution having the lowest risk.
The problem is that leak you see in the picture. I really can't get where it comes from.
Here's the code:
#include "Analyzer.h"
#define INFINITY 999999999
// functions prototypes
bool areFullyCompatible(int *, int, string);
bool contains(int *, int, int);
bool selectionComplete(int , int);
void extractNodes(string , int *, int &, int);
void addNodes(int *, int &, string);
Analyzer::Analyzer(Graph *graph, string *prints, int printsLen) {
this->graph = graph;
this->prints = prints;
this->printsLen = printsLen;
this->actualResult = new string[graph->nodesNum];
this->bestResult = new string[graph->nodesNum];
this->bestReSize = INFINITY;
this->bestRisk = INFINITY;
this-> actualSize = -1;
}
void Analyzer::getBestResult(int &size) {
for (int i = 0; i < bestReSize; i++)
cout << bestResult[i] << endl;
}
void Analyzer::analyze() {
// the number of selected paths is at most equal to the number of nodes
int maxSize = this->graph->nodesNum;
float totRisk;
int *actualNodes = new int[maxSize];
int nodesNum;
bool newCycle = true;
for (int i = 0; i < printsLen - 1; i++) {
for (int j = i + 1; j < printsLen; j++) {
// initializing the current selection
if (newCycle) {
newCycle = false;
nodesNum = 0;
extractNodes(prints[i], actualNodes, nodesNum, maxSize);
this->actualResult[0] = prints[i];
this->actualSize = 1;
}
// adding just fully compatible prints
if (areFullyCompatible(actualNodes, nodesNum, prints[j])) {
this->actualResult[actualSize] = prints[j];
actualSize++;
addNodes(actualNodes, nodesNum, prints[j]);
}
if (selectionComplete(nodesNum, maxSize)) {
// it means it's no more a possible best solution with the minimum number of paths
if (actualSize > bestReSize) {
break;
}
// calculating the risk associated to the current selection of prints
totRisk = calculateRisk();
// saving the best result
if (actualSize <= bestReSize && totRisk < bestRisk) {
bestReSize = actualSize;
bestRisk = totRisk;
for(int k=0;k<actualSize; k++)
bestResult[k] = actualResult[k];
}
}
}
newCycle = true;
}
}
float Analyzer::calculateRisk() {
float totRisk = 0;
int maxSize = graph->nodesNum;
int *nodes = new int[maxSize];
int nodesNum = 0;
for (int i = 0; i < actualSize; i++) {
extractNodes(this->actualResult[i], nodes, nodesNum, maxSize);
// now nodes containt all the nodes from the print but 0, so I add it (it's already counted but misses)
nodes[nodesNum-1] = 0;
// at this point I use the graph to calculate the risk
for (int i = 0; i < nodesNum - 1; i++) {
float add = this->graph->nodes[nodes[i]].edges[nodes[i+1]]->risk;
totRisk += this->graph->nodes[nodes[i]].edges[nodes[i+1]]->risk;
//cout << "connecting " << nodes[i] << " to " << nodes[i + 1] << " with risk " << add << endl;
}
}
delete nodes;
return totRisk;
}
// -------------- HELP FUNCTIONS--------------
bool areFullyCompatible(int *nodes, int nodesNum, string print) {
char *node;
char *dup;
int tmp;
bool flag = false;
dup = strdup(print.c_str());
node = strtok(dup, ",");
while (node != NULL && !flag)
{
tmp = atoi(node);
if (contains(nodes, nodesNum, tmp))
flag = true;
node = strtok(NULL, ",");
}
// flag signals whether an element in the print is already contained. If it is, there's no full compatibility
if (flag)
return false;
delete dup;
delete node;
return true;
}
// adds the new nodes to the list
void addNodes(int *nodes, int &nodesNum, string print) {
char *node;
char *dup;
int tmp;
// in this case I must add the new nodes to the list
dup = strdup(print.c_str());
node = strtok(dup, ",");
while (node != NULL)
{
tmp = atoi(node);
if (tmp != 0) {
nodes[nodesNum] = tmp;
nodesNum++;
}
node = strtok(NULL, ",");
}
delete dup;
delete node;
}
// verifies whether a node is already contained in the nodes list
bool contains(int *nodes, int nodesNum, int node) {
for (int i = 0; i < nodesNum; i++)
if (nodes[i] == node)
return true;
return false;
}
// verifies if there are no more nodes to be added to the list (0 excluded)
bool selectionComplete(int nodesNum, int maxSize) {
return nodesNum == (maxSize-1);
}
// extracts nodes from a print add adds them to the nodes list
void extractNodes(string print, int *nodes, int &nodesNum, int maxSize) {
char *node;
char *dup;
int idx = 0;
int tmp;
dup = strdup(print.c_str());
node = strtok(dup, ",");
while (node != NULL)
{
tmp = atoi(node);
// not adding 0 because every prints contains it
if (tmp != 0) {
nodes[idx] = tmp;
idx++;
}
node = strtok(NULL, ",");
}
delete dup;
delete node;
nodesNum = idx;
}
You have forgotten to delete several things and used the wrong form of delete for arrays where you have remembered, e.g.
float Analyzer::calculateRisk() {
float totRisk = 0;
int maxSize = graph->nodesNum;
int *nodes = new int[maxSize];
//...
delete [] nodes; //<------- DO THIS not delete nodes
The simplest solution is to avoid using raw pointers and use smart ones instead. Or a std::vector if you just want to store stuff somewhere to index into.
You have new without corresponding delete
this->actualResult = new string[graph->nodesNum];
this->bestResult = new string[graph->nodesNum];
These should be deleted somewhere using delete [] ...
You allocate actualNodes in analyze() but you don't release the memory anywhere:
int *actualNodes = new int[maxSize];
In Addition, Analyzer::bestResult and Analyzer::actualResult are allocated in the constructor of Analyzer but not deallocated anywhere.
this->actualResult = new string[graph->nodesNum];
this->bestResult = new string[graph->nodesNum];
If you must use pointers, I really suggest to use smart pointers, e.g. std::unique_ptr and/or std::shared_ptr when using C++11 or later, or a Boost equivalent when using C++03 or earlier. Otherwise, using containers, e.g. std::vector is preferred.
PS: You're code also has a lot of mismatches in terms of allocation and deallocation. If memory is allocated using alloc/calloc/strdup... it must be freed using free. If memory is allocated using operator new it must be allocated with operator delete. If memory is allocated using operator new[] it must be allocated with operator delete[]. And I guess you certainly should not delete the return value of strtok.

Memory for array property not allocated before Constructor?

When I run the program and new a NetworkEditor, it will corrupt at the constructor because of it reads out of the array's memory.
When I debug it one loop by one loop, it will be ok!?
Why? Didn't it allocate enough memory for the array before it entered the constructor?
In my class, I have two properties:
/*NetworkEditor.h*/
class CNetworkEditor : public CDiagramEditor
{...
VLLink* VL_list[10];
VLLink* temp_VL_list[10];
}
and in the constructor, I initialize the arraies:
/*NetworkEditor.cpp*/
for (int i = 0; i < 10; i++)
{
VLLink* vl_link = NULL;
while(vl_link == NULL)
{
vl_link = new VLLink;
}
vl_link->preLink = NULL;
vl_link->nextLink = NULL;
vl_link->link = NULL;
VLLink* vl_link2 = NULL;
while (vl_link2 == NULL)
{
vl_link2 = new VLLink;
}
vl_link2->preLink = NULL;
vl_link2->nextLink = NULL;
vl_link2->link = NULL;
VL_list[i] = vl_link;
temp_VL_list[i] = vl_link2;
}
and VLLink is defined as:
typedef struct struct_VLLink
{
CPhysicalLink* link;
struct_VLLink* preLink;
struct_VLLink* nextLink;
}VLLink;
If I change it to:
VLLink* VL_list2[10];
VLLink* temp_VL_list2[10];
for (int i = 0; i < MAX_VL_NUM; i++)
{
VLLink* vl_link = NULL;
while(vl_link == NULL)
{
vl_link = new VLLink;
}
vl_link->preLink = NULL;
vl_link->nextLink = NULL;
vl_link->link = NULL;
VLLink* vl_link2 = NULL;
while (vl_link2 == NULL)
{
vl_link2 = new VLLink;
}
vl_link2->preLink = NULL;
vl_link2->nextLink = NULL;
vl_link2->link = NULL;
VL_list2[i] = vl_link;
temp_VL_list2[i] = vl_link2;
}
It will be ok!?
Apart from #PeterHuene's suggestion to replace VL_list and temp_VL_list with something like std::list<CPhysicalLink> or similar, you should move the initialization of VLLink into the constructor, avoiding the code duplication in your loop
struct VLLink {
VLLink() : link(NULL), prelink(NULL), nextlink(NULL) {}
...
};`
then you can reduce your loop as #MikeSeymour said
for (int i = 0; i < MAX_VL_NUM; i++) {
VL_list[i] = new VLLink();
temp_VL_list[i] = new VLLink();
}
A reason for your memory problem might be, that MAX_VL_NUM is larger than 10. So, you should either use MAX_VL_NUM everywhere or use 10 everywhere.
And now to your question ;-)
If I change it to ... It will be ok!?
Nobody can answer this, because nobody knows what you want to achieve. My first reaction would be definitely No!, because moving variables around "just because" is almost always a bad idea. It's better to analyze the problem and fix the cause than to cure some random symptoms.
Your change would also modify the meaning from member of a class to automatic variable on the stack.

Why am I leaking memory here (depth first search) c++?

int Solver::negamax(Position* pos,int alpha,int beta, int color, int depth ) {
if(depth==0 || is_final(pos)){
return evaluate(pos);
}
else{
vector < Position* > moves = generate_moves(pos->get_board());
vector < Position* >::iterator move;
int min = 99999;
for(move = moves.begin(); move < moves.end(); move++){
int val = negamax(*move,alpha, beta, -color, depth - 1 );
if(val <= min){
min = val;
delete best;
best = NULL;
best = (*move)->get_board();
}
else{
delete *move; //So this isnt cleaning up?
*move = NULL;
}
}
min = -min;
return min;
}
}
vector < Position* > TakeAwaySolver::generate_moves(Board *brd){
TakeAwayBoard *board = static_cast<TakeAwayBoard*>(brd);
vector < Position* > moves;
if(board->get_data() >= 3){
TakeAwayBoard *b = new TakeAwayBoard(board->get_data() - 3);
Position* p = new Position(b);
moves.push_back(p);
}
if(board->get_data() >= 2){
TakeAwayBoard *b = new TakeAwayBoard(board->get_data() - 2);
Position* p = new Position(b);
moves.push_back(p);
}
TakeAwayBoard *b = new TakeAwayBoard(board->get_data() - 1);
Position* p = new Position(b);
moves.push_back(p);
return moves;
}
I valgrinded my program and I'm apparently leaking memory. It seems that I'm deleting all unused objects, but perhaps I'm not understanding something. generate_moves() does allocate memory for each of the objects being pushed in. Evaluate returns 1. Does it seem possible that I'm leaking memory in any location?
You have an if/else in which *move is only deleted in one of the paths. I'd check there.
for(move = moves.begin(); move < moves.end(); move++){
int val = negamax(*move,alpha, beta, -color, depth - 1 );
if(val <= min){
min = val;
delete best;
best = NULL;
best = (*move)->get_board();
//best is deleted, but *move is not
}
else{
delete *move;
*move = NULL;
}
}
A std::vector<position *> container will not automatically delete the inserted elements when it is destroyed. Make it a std::vector<x<position *> > where x is some suitable smart pointer template, like auto_ptr.
If you don't want to do that, then the next best thing is to wrap the vector in a class whose destructor iterates over the vector and calls delete on every pointer.
I.e. this is a memory leak:
{
std::vector<int *> vec;
vec.push_back(new int[3]);
// vec goes out of scope
}
Sure, the vector cleans itself up! It deletes its internal array, etc. But it does nothing with the new int[3] that we allocated and put into the vector.
It seems to me that you never clear the 'minimum' positions.
You store a pointer to the board in best, and take care to clear that when you replace it with a better minimum, and in case the move isn't a minimum so far, you properly clean it up, but you never clean the actual position pointer in case it's a minimum.
As a side note, this is redundant:
best = NULL;
best = (*move)->get_board();