Solved

deleting an array of pointers

Posted on 2002-07-20
3
225 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
Comment Utility
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
Comment Utility
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
Comment Utility
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

How to improve team productivity

Quip adds documents, spreadsheets, and tasklists to your Slack experience
- Elevate ideas to Quip docs
- Share Quip docs in Slack
- Get notified of changes to your docs
- Available on iOS/Android/Desktop/Web
- Online/Offline

Join & Write a Comment

Templates For Beginners Or How To Encourage The Compiler To Work For You Introduction This tutorial is targeted at the reader who is, perhaps, familiar with the basics of C++ but would prefer a little slower introduction to the more ad…
Introduction This article is a continuation of the C/C++ Visual Studio Express debugger series. Part 1 provided a quick start guide in using the debugger. Part 2 focused on additional topics in breakpoints. As your assignments become a little more …
The viewer will learn how to clear a vector as well as how to detect empty vectors in C++.
The viewer will be introduced to the technique of using vectors in C++. The video will cover how to define a vector, store values in the vector and retrieve data from the values stored in the vector.

771 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

Need Help in Real-Time?

Connect with top rated Experts

15 Experts available now in Live!

Get 1:1 Help Now