You are here:

# C++/Memory Leak with vectors

Question
QUESTION: Hi,

I have a program in C++ that is leaking memory while pushing data to the vector. My problem is that I don't know why this is doing that and how to fix it. Here is my code. Any help will be greatly appreciate it.
Note: The vector uses the structure pixArea

typedef struct{
int x;
int y;
int pix;
} pixArea;

pixArea temp1;

for (ypos=y3; ypos < (y3+y3Height); ypos++)
{
for (xpos=x3; xpos < (x3+x3Width); xpos++)
{
pixa=*(im_src0 + xpos + (LineLength * (ypos)));
temp1.x=xpos; temp1.y=ypos; temp1.pix=pixa;
if(pixa<bThresh3) {pixBDefect.push_back(temp1);}
if(pixa>wThresh3) {pixWDefect.push_back(temp1);}
}
}

Mirtha

ANSWER: I noticed that you have not declared the pixa over here. Please, do tell me that it is a vector.

---------- FOLLOW-UP ----------

QUESTION: Thanks Rakshitha,

This is a part of a program where  the structure pixArea is composed of 3 integers one of them is pixa (pixa can't be a vector). My vectors are A and B and they are expecting the elements of the type pixArea (which is a structure).

The for loop is scanned every 300ms and I have a leaking in this loop. I tried using the method A.clear() and B.clear() to remove the data inside the vectors before entering to the loop but it didn't help at all.

So I don't know if I should forget vectors and use a different alternative.

//this is declared in my header file
---------------------------
vector<pixArea> A;
vector<pixArea> B;

typedef struct{
int x;
int y;
int pix;
} pixArea;
---------------------------

//declared in my cpp file
---------------------------
pixArea temp1; //creaing a temporal pixArea
int pixa;
int LineLength=100;
int limitA=100;
int limitB=200;
int y3=10;
int x3=10;

Mymethod(BYTE *image)
{
A.clear();
B.clear();

for (int ypos=y3; ypos < 50; ypos++)
{
for (int xpos=x3; xpos < 50; xpos++)
{
pixa=*(image+ xpos + (LineLength * (ypos)));

temp1.x=xpos;
temp1.y=ypos;
temp1.pix=pixa;

if(pixa<limitA) {A.push_back(temp1);}
if(pixa>limitB) {B.push_back(temp1);}
}
}
}

pixa=*(image+ xpos + (LineLength * (ypos)));
Hi one more question. Here you are passing image as a pointer. Are you adding the adress of image here in the above expression. Also, I am not sure about method clear? You should use erase to remove data from the vector.Please, go through the website about using erase method. Hope my answer helped you.

http://www.codersource.net/c++_vector_stl.html

C++

Volunteer

#### rakshitha

##### Expertise

Difficult questions related to C .

##### Experience

C ,vc ,opc ,windows CE, ActiveX

Education/Credentials
Masters in electrical engineering