Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations bkrike on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

passing arrays and allocating memory

Status
Not open for further replies.

piofenton

Instructor
Jul 12, 2002
33
IE
Hi,
I have this code which I am trying to get to grips with (it was written by another). I am unsure as to whether it is giving me a memory leak. Some of you may be able to help. I have an array which is passed as a paramater to the function allocate2darray2. In here the pointer to the array is allocated memory using new. Why does this need to happen? Alos where should this memory be freed if it is allocated within the function?

Here is the code (I'm not sure if I explained it ok!)
Declaration
int** sch2;
void allocate2DArray2(int** &array, int nbline);
Call
schemaSize_2.allocate2DArray2(sch2,schemaSize_2.findSize()*2);
Definition
void schemaStats::allocate2DArray2(int** &array,int nbline){
// Create and initialise the 2D dynamic array.
array = new int*[nbline];
for (int k=0;k<nbline;k++) array[k]=new int[nbline];
// Go over the hashtable using an iterator and fill the array.
int i=0;
int x=0;
for(H_Table::const_iterator it(_hashTable.begin());it!=_hashTable.end();it++){
x=0;
for (int j=i;j<i+_schemaSize;j++){
array[j][0]=it->second.tab[x]; // The schema.
array[j][1]=it->second.nbOcc; // His occurrences.
x++;
}
i=i+_schemaSize;
}
}

The sch2 array is freed at some point later in the program.

Any ideas that can shed light would be appreciated.
 
OMG, my eyes are bleeding! Adding some spaces would make it a LOT more readable... :)

How is the array being deleted?

It should be deleted something like this:
Code:
for ( int nCount = 0; nCount < nbline; ++nCount )
{
    delete [] array[nCount];
}

delete [] array;
 
Thanks for your reply cpjust!
Sorry bout the lack of spaces!

My point is though is whether the array named "array" in the function defintion should be deleted or need it only be the "sch2" from the function call which should be deleted?
 
> My point is though is whether the array named "array" in the
> function defintion should be deleted or need it only be the
> "sch2" from the function call which should be deleted?

Allocated object should be deleted only once - if you would delete allocated array pointed by parameter of the function "array", it will be unaccessible for the caller, so, if you want to return allocated object - it should be deleted by the caller after use, following cpjust's advice:
for(k=0; k < schemaSize...; k++) delete [] sch2[k];
delete [] sch2;
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top