Solved

deleting an array of pointers

Posted on 2002-07-20
3
232 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
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
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

On Demand Webinar: Networking for the Cloud Era

Did you know SD-WANs can improve network connectivity? Check out this webinar to learn how an SD-WAN simplified, one-click tool can help you migrate and manage data in the cloud.

Question has a verified solution.

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

Article by: SunnyDark
This article's goal is to present you with an easy to use XML wrapper for C++ and also present some interesting techniques that you might use with MS C++. The reason I built this class is to ease the pain of using XML files with C++, since there is…
This article shows you how to optimize memory allocations in C++ using placement new. Applicable especially to usecases dealing with creation of large number of objects. A brief on problem: Lets take example problem for simplicity: - I have a G…
The goal of the video will be to teach the user the difference and consequence of passing data by value vs passing data by reference in C++. An example of passing data by value as well as an example of passing data by reference will be be given. Bot…
The viewer will learn additional member functions of the vector class. Specifically, the capacity and swap member functions will be introduced.

631 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