Dave
Dave

Reputation: 17

How do you delete an empty array of objects?

I am trying to create a constructor that deletes a directory objects name, then the subdirectories within the directory, and finally the directory itself. The delete [] *subDirectories line however causes segfaults whenever used.

Subdirectories are allocated by

subDirectories[subDirectoryCount++] = new Directory(arguments[1], umask, time, this); 

Directory::~Directory()
{
    delete [] name;

    for (int i = 0; i < subDirectoryCount; i++)
       delete subDirectories[i];
    delete [] *subDirectories;
}

Upvotes: 1

Views: 1230

Answers (1)

Sarfaraz Nawaz
Sarfaraz Nawaz

Reputation: 361402

Write:

delete [] subDirectories; 

Make sure subDirectories is allocated using new [].

Anyway, stop doing that either. Use std::vector<std::unique_ptr<Directory>> instead, Or std::vector<std::shared_ptr<Directory>> if the elements are to be shared. Either way let the library manage memory for you.

Upvotes: 6

Related Questions