Solved

deleting an array of pointers

Posted on 2002-07-20
3
230 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

Networking for the Cloud Era

Join Microsoft and Riverbed for a discussion and demonstration of enhancements to SteelConnect:
-One-click orchestration and cloud connectivity in Azure environments
-Tight integration of SD-WAN and WAN optimization capabilities
-Scalability and resiliency equal to a data center

Question has a verified solution.

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

Suggested Solutions

Title # Comments Views Activity
SetCurrentDirectory path limit 7 131
C++ assignment question 7 236
C language IDE – Compilers installation 14 75
C++ question 3 70
Errors will happen. It is a fact of life for the programmer. How and when errors are detected have a great impact on quality and cost of a product. It is better to detect errors at compile time, when possible and practical. Errors that make their wa…
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…
The goal of the tutorial is to teach the user how to use functions in C++. The video will cover how to define functions, how to call functions and how to create functions prototypes. Microsoft Visual C++ 2010 Express will be used as a text editor an…
The viewer will learn how to use the return statement in functions in C++. The video will also teach the user how to pass data to a function and have the function return data back for further processing.

856 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