0

I know that pointers are a lot like arrays (if not one and the same) in a way, but I'm having trouble deciphering when I should explicitly delete a pointer.

Take this code for example:

#include <vector>

int main(int argc, char** argv)
{
    std::vector<char*> strings;

    strings.push_back(argv[0]);
    return 0;
}

Now obviously, no one in their right mind would make a program exactly like this, but for pure discussion, let's say this is my program. Should I have deleted strings.at(0) to avoid a memory leak there, or is the data considered a character array to be destroyed when the program terminates?

Similarly, suppose I have a vector of a class I've created, and I've declared them all as new instances of the class. Do I then need to delete, or is it fine?

I'm a self-taught programmer, so these complicated (and sometimes dangerous) concepts make me paranoid.

2mac
  • 1,609
  • 5
  • 20
  • 35
  • 1
    You've been badly misinformed; pointers and arrays are not *at all* the same thing. Read section 6 of the [comp.lang.c FAQ](http://www.c-faq.com/); it applies to C++ as well. – Keith Thompson Mar 22 '14 at 02:35
  • As a self-taught programmer interested in memory management, I believe you should take a look (if you haven't already) at how smart pointers work in C++11 – Natan Streppel Mar 22 '14 at 02:37

2 Answers2

3

As a rule, you should free or delete anything you malloc or new.

With the vector, when you push into a vector, it does a copy. So a copy of a pointer just copies the address that the pointer points to, not the actual data pointed to.

To answer your question, you should not free argv[0] since you didn't malloc it - see Where does the OS store the command line arguments? for an explanation.

If you new your own class, then you should delete the entries in the vector and then clear it (per Claudiordgz's answer).

EDIT since the answer was deleted, you can do something like:

for(auto it = strings.begin(); it != strings.end(); ++it)
{
  delete *it;
}
strings.clear()

(direct copy from the referenced answer)

Community
  • 1
  • 1
NG.
  • 22,560
  • 5
  • 55
  • 61
1

Local variable -> allocated on stack -> gets destroyed automatically when function exits.
Dynamically allocated variables -> allocated on heap -> need to delete them after use.

If you have a program that runs non-stop, say some daemon/background process. And you allocated a lot of dynamic variables using new and you do that frequently in your code. Then, with time the memory requirement of your running program will increase since you are not deleting them, to a point that you are no more able to allocate more memory.

And if, it's a small program that exits, the OS generally reclaims the memory, but it's the job of the programmer to not to leave it to the OS to reclaim the memory.

brokenfoot
  • 11,083
  • 10
  • 59
  • 80