1

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;
}
2
  • 2
    delete [] subDirectories. Make sure subDirectories was created with new[], otherwise you have undefined behavior. Commented Feb 4, 2015 at 18:46
  • 5
    If it's C++ should definitively avoid C style array and use std containers like std::vector Commented Feb 4, 2015 at 18:52

1 Answer 1

6

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.