Solved

deleting an array of pointers

Posted on 2002-07-20
3
229 Views
Last Modified: 2010-04-01
Hi all.
I am having a Tad of grief trying to delete an array of string pointers.
Basicly, what it does is searches for several files and counts them. Then it creates an array to hold the number of files. Then it cycles through the array to set the size & place the name of the file.
I call the routine quite a lot and I have traced a memory leak to this.
How should I delete it? I have put what I've tried down below the code;

char **Files;
WIN32_FIND_DATA FoundData;
HANDLE FindHandle;
int filecount = 0;
FindHandle = FindFirstFile(
    "*.alm",     // pointer to name of file to search for
    &FoundData      // pointer to returned information
   );
if(INVALID_HANDLE_VALUE != FindHandle)
{
filecount++;
while(FindNextFile(

    FindHandle,     // handle to search
    &FoundData      // pointer to structure for data on found file
   ))
{
filecount++;
}
while(!FindClose( FindHandle/* file search handle*/ ))
{
}

Files = new char*[filecount];
FindHandle = FindFirstFile(
    "*.alm",     // pointer to name of file to search for
    &FoundData      // pointer to returned information
   );

if(INVALID_HANDLE_VALUE != FindHandle)
{
Files[0] = new char[strlen(FoundData.cFileName)+1];
strcpy(Files[0],FoundData.cFileName);
for(int i =1; i<filecount;i++)
{
FindNextFile(
    FindHandle,     // handle to search
    &FoundData      // pointer to structure for data on found file
        ) ;
Files[i] = new char[strlen(FoundData.cFileName)+1];
strcpy(Files[i],FoundData.cFileName);
}
}//end 2nd if(FindHandle)

}//end if(FindHandle)


/*delete attempt 1*/
delete []Files;

/*delete attemp 2*/
delete []*Files;

/*delete attemp 3*/
for(int i =0; i<filecount;i++)
{
        delete Files[i];
}
delete Files;


Thanks

David
0
Comment
Question by:dsch
3 Comments
 
LVL 86

Expert Comment

by:jkr
ID: 7167228
Change

delete Files;

to read

delete[] Files;

If you want to delete a vector, you have to use "delete[]"
0
 
LVL 8

Accepted Solution

by:
fl0yd earned 50 total points
ID: 7167294
attempt 3 is almost correct:

for( unsigned int i = 0; i < filecount; ++i )
    delete [] Files[i];

delete [] Files;

You allocated an array of pointers to char-arrays. You then filled this array with the addresses of newly allocated c-strings. That is why you have to delete the c-strings (i.e. arrays of char's) in a loop before deleting the array holding the pointers to them. You could also use the STL to make things easier for you:

#include <vector>
#include <string>

std::vector<std::string> files;

WIN32_FIND_DATA FoundData = { 0 };
HANDLE FindHandle = INVALID_HANDLE_VALUE;

FindHandle = FindFirstFile(
   "*.alm",     // pointer to name of file to search for
   &FoundData      // pointer to returned information
  );
if( INVALID_HANDLE_VALUE != FindHandle ) {

    // put first file in the list/vector
    files.push_back( std::string( FoundData.cFileName ) );
    while( FindNextFile( FindHandle,  &FoundData ) )
        // keep pushing files into the list
        files.push_back( std::string( FoundData.cFileName ) );

    FindClose( FindHandle/* file search handle*/ );
}

// if you still need the number of files:
unsigned int filecount = files.size();

There is some overhead involved both in std::string's as well as std::vector's (if you don't need random access you could also use std::list). It isn't all that bad though and certainly not as time-consuming as running your loop twice.
0
 
LVL 1

Author Comment

by:dsch
ID: 7167505
Thanks jkr but that was the same as my first attempt.

fl0yd:
Yes, I though option three was the correct way, I had just implemented it a bit wrong. Cheers.

I also verified this method in the Borland help file under delete which gave this example.
It may help others if I post it.
Thanks again
David

// ALLOCATE A TWO-DIMENSIONAL SPACE, INITIALIZE, AND DELETE IT.

#include <exception>
#include <iostream.h>

void display(long double **);
void de_allocate(long double **);

int m = 3;                               // THE NUMBER OF ROWS.
int n = 5;                               // THE NUMBER OF COLUMNS.

int main(void) {
   long double **data;

   try {                                 // TEST FOR EXCEPTIONS.
      data = new long double*[m];        // STEP 1: SET UP THE ROWS.
      for (int j = 0; j < m; j++)
          data[j] = new long double[n];  // STEP 2: SET UP THE COLUMNS

      }
   catch (std::bad_alloc) {  // ENTER THIS BLOCK ONLY IF bad_alloc IS THROWN.
      // YOU COULD REQUEST OTHER ACTIONS BEFORE TERMINATING
      cout << "Could not allocate. Bye ...";
      exit(-1);
      }

   for (int i = 0; i < m; i++)
      for (int j = 0; j < n; j++)
          data[i][j] = i + j;            // ARBITRARY INITIALIZATION

   display(data);
   de_allocate(data);
   return 0;
   }

void display(long double **data) {
   for (int i = 0; i < m; i++) {

        for (int j = 0; j < n; j++)
             cout << data[i][j] << " ";
       cout << "\n" << endl;
       }
   }

void de_allocate(long double **data) {
   for (int i = 0; i < m;  i++)
       delete[] data[i];                 // STEP 1: DELETE THE COLUMNS

   delete[] data;                        // STEP 2: DELETE THE ROWS

   }
0

Featured Post

DevOps Toolchain Recommendations

Read this Gartner Research Note and discover how your IT organization can automate and optimize DevOps processes using a toolchain architecture.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Title # Comments Views Activity
Visual c++ and text files 7 67
object modeling - load and save functions 5 61
Unable to start eclipse ? 17 141
Least Squares Curve Fitting 4 77
In days of old, returning something by value from a function in C++ was necessarily avoided because it would, invariably, involve one or even two copies of the object being created and potentially costly calls to a copy-constructor and destructor. A…
Many modern programming languages support the concept of a property -- a class member that combines characteristics of both a data member and a method.  These are sometimes called "smart fields" because you can add logic that is applied automaticall‚Ķ
The viewer will learn how to pass data into a function in C++. This is one step further in using functions. Instead of only printing text onto the console, the function will be able to perform calculations with argumentents given by the user.
The viewer will learn additional member functions of the vector class. Specifically, the capacity and swap member functions will be introduced.

770 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question