Thread: using delete

  1. #1
    Registered User
    Join Date
    Nov 2005
    Posts
    38

    using delete

    How can I use delete to free up the memory in a 2D array? Do I need to call it for each of the rows in the array??

    So say if I have

    Code:
    char **args = new char*[argc];
    for(int i=0; i < argc; ++i) {
        args[i] = new char[strlen(argv[i])+1];
        strycpy(args[i], argv[i]);
    }
    And then I would like to free up the memory. Do I have to do something like the following:

    Code:
    for(int i=0; i < argc; ++i) {
        delete [] args[i];  
    }
    
    delete [] args;
    or do I just need to do

    Code:
    delete [] args;
    Also, how can I tell if the memory has been freed??
    And could anyone suggests a good tutorial on memory allocation in C++?

    Thanks
    Mark

  2. #2
    Bond sunnypalsingh's Avatar
    Join Date
    Oct 2005
    Posts
    162
    This is right
    Code:
    for(int i=0; i < argc; ++i) 
    {
        delete [] args[i];  
    }
    delete [] args;

  3. #3
    Registered User
    Join Date
    Jan 2005
    Posts
    7,366
    For every new[], you should have a matching delete [], which is why your first try is correct.

    >> Also, how can I tell if the memory has been freed??

    You cannot tell in code if memory is freed or not. You just need to design and code your program so that it always will be. Once you're running your code, there are different tools that you can use to detect memory leaks due to unfreed memory. Those depend on your compiler/IDE, platform, and how much effort you want to put into detecting the leaks.

    Another, better way to handle memory management in C++ is to let the built-in tools do the work for you. For example, standard classes like vector are better solutions for dynamic arrays like you are using because they handle the allocation and deallocation of memory for you. The memory is automatically freed by the vector. The code for the allocation of your array of C style strings with the standard vector and string classes would be:
    Code:
    std::vector<std::string> args(argc);
    for(int i=0; i < argc; ++i) {
      args[i] = argv[i];
    }
    And the cleanup code would look like this:
    Code:
    // nothing required here

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Proper Usage of the delete Operator
    By thetinman in forum C++ Programming
    Replies: 7
    Last Post: 04-25-2007, 11:53 PM
  2. BST delete again, but this time I think I'm close
    By tms43 in forum C++ Programming
    Replies: 9
    Last Post: 11-05-2006, 06:24 PM
  3. delete and delete []
    By Lionel in forum C++ Programming
    Replies: 8
    Last Post: 05-19-2005, 01:52 PM
  4. why is this prog crashing on delete?
    By Waldo2k2 in forum Windows Programming
    Replies: 2
    Last Post: 12-04-2002, 11:17 PM
  5. Problem need help
    By Srpurdy in forum C++ Programming
    Replies: 1
    Last Post: 07-24-2002, 12:45 PM