Why do I need to delete []?

Say I have a function like this:

int main() { char* str = new char[10]; for(int i=0;i<5;i++) { //Do stuff with str } delete[] str; return 0; } 
  • Why do I need to remove str if I finish the program anyway? I would not care if this memory goes to a land full of unicorns, if I'm just going to go out, right?

  • Is this just good practice?

  • Does it have deeper consequences?

+44
c ++ memory-management memory memory-leaks delete-operator
Mar 18 '13 at 22:24
source share
15 answers

If your question is actually: "I have this trivial program, is it normal that I do not release a few bytes before it comes out?" The answer is yes, that’s good. In any modern operating system it will be perfect. And the program is trivial; it doesn't look like you're going to put it in a pacemaker or run a Toyota Camry brake system with this thing. If the only customer is that you are the only one you can influence by being sloppy, you.

Then the problem arises when you start to generalize to non-trivial cases from the answer to this question asked about the trivial case.

So let me ask you two questions about some non-trivial cases instead.

I have a long-term service that allocates and frees memory in complex ways, possibly involving multiple allocators that hit several heaps. Shutting down the service in normal mode is a complex and time-consuming process, which involves the constant closure of external states - files, databases, etc. Do I have to ensure that every byte of memory that I have allocated is freed before I shut down?

Yes, and I will tell you why. One of the worst things that can happen to a long-term service is an accidental memory leak. Even tiny leaks can eventually reach huge leaks. The standard method for finding and fixing memory leaks is a heap allocation tool, so that when they are turned off, they record all resources that have ever been allocated without being freed. If you do not want to chase a lot of false positives and spend a lot of time in the debugger, always free up your memory, even if it is not strictly necessary.

The user already expects the shutdown of the service to take billions of nanoseconds, so who needs it if you cause a little extra pressure on the virtual dispenser, making sure that everything is cleaned up? This is just the price you pay for a lot of complex software. And it doesn't look like you are shutting down the service all the time, so again, who cares if its a few milliseconds slower than it could be?

I have the same long-term service. If I find that one of my internal data structures is damaged, I want to "quickly fail." The program is in undefined state, it most likely works with elevated privileges, and I'm going to assume that if I detect a damaged state, this is because my service is actively attacked by hostile parties. The safest thing to do is to close the service immediately. I would prefer that the attackers refuse to serve customers, rather than risking staying away from the service and compromising the data of my users. In this crash scenario, should I make sure that every byte of memory that I allocated is freed?

Of course not. The operating system will take care of this for you. If your heap is damaged, attackers can hope that you free up memory as part of your exploit. Every milliseconds are counted. And why did you bother polishing the door handles and wiping the kitchen before throwing tactical nuclear weapons at the building?

So, the answer to the question "should I free up memory before the exit of my program?" "it depends on what your program does."

+73
Mar 19 '13 at 0:58
source share

Yes, this is a good practice. You should NEVER assume that your OS will take care of freeing up memory, if you take up this habit, it will hurt you in the future.

To answer your question, however, when you exit the main state, the OS frees all the memory stored in this process, so it includes any threads that you may have generated or allocated variables. The OS will take care to free this memory for other users.

+39
Mar 18 '13 at 22:27
source share

Important note: delete freeing up memory is almost just a side effect. The important thing he does is destroy the object. With RAII designs, this can mean anything: close files, release OS handles, terminate streams, or delete temporary files.

Some of these actions will be handled by the OS automatically when your process exits, but not all.

In your example, there is no reason NOT to call delete . but there is no reason to call new , so you can get around the problem this way.

 char str[10]; 

Or you can bypass deletion (and related security issues) with smart pointers ...

So, as a rule, you should always make sure that your lifetime is properly managed.

But this is not always easy: workarounds for the static initialization fiasco order often mean that you have no choice but to rely on an OS that clears a few singleton types for you.

+24
Mar 18 '13 at 22:47
source share

The opposite answer: No, this is a waste of time. A program with a huge amount of highlighted data should touch almost every page to return all distributions to a free list. This takes up processor time, creates memory pressure for uninteresting data, and possibly even forces the process to exchange pages from disk. A simple shutdown frees all memory back to the OS without any further action.

(not that I disagree with the reasons for “Yes,” I just think there are arguments in both directions)

+16
Mar 18 '13 at 22:35
source share

Your operating system should take care of the memory and clean it when you exit your program, but in general it is good practice to free the memory that you have reserved. I think that it’s best to personally delve into the correct way of thinking about this, because while you are doing simple programs, you are most likely doing this in order to learn.

In any case, the only way to guarantee the release of memory is to do it yourself.

+6
Mar 18 '13 at 22:29
source share

new and delete are reserved keywords . They must interact with each other through the code block or through the parent lifecyle object. When the younger brother makes a mistake, the older brother wants to delete it. Then the mother (your program) will be happy and proud of them.

+4
Mar 19 '13 at 7:35
source share

I can no longer agree with Eric Lippert:

So, the answer to the question "should I free up memory before the exit of my program?" "it depends on what your program does."

The other answers here provided arguments for and against both, but the real point is what your program does . Consider a more non-trivial example, in which an instance of a type that is dynamically allocated is a user class, and the class destructor performs some actions that cause a side effect . In such a situation, the argument of a memory leak or not is trivial, the more important problem is the inability to call delete on such an instance of the class will lead to Undefined behavior.

[basic.life] 3.8 Object lifetime
Paragraph 4:

A program can end the lifetime of any object by reusing the storage that the object occupies, or by explicitly calling the destructor for an object of the class type with a non-trivial destructor. For an object of class type with a nontrivial destructor, the program does not require a direct call to the destructor before the storage that the object occupies is reused or freed; however , if there is no explicit call to the destructor or if the delete expression (5.3.5) is not used to free the storage, the destructor should not be implicitly called, and any program that depends on side effects by the destructor has not determined the behavior.

So, the answer to your question: as Eric says, “depends on what your program does”

+3
Mar 19 '13 at 4:34 on
source share

This is a fair question, and there are a few things to consider when answering:

  • Some objects have more complex destructors that not only free up memory when they are deleted. They may have other side effects that you do not want to miss.
  • It is not guaranteed by the C ++ standard that your memory will be freed when the process terminates. (Of course, on a modern OS, it will be released, but if you were on some strange OS that didn’t do this, you would need to free the memory correctly.
  • on the other hand, launching destructors upon exiting the program can take a lot of time, and if all this is a release memory (which will be released anyway), then yes, it makes sense to just short-circuit and exit immediately.
+2
Mar 20 '13 at 7:28
source share

Most operating systems return memory when they exit the process. Exceptions may include certain RTOS, old mobile devices, etc.

In the absolute sense, your application will not leak memory; however, it is good practice to clear the memory that you allocate, even if you know that it will not cause a real leak. This problem is associated with leaks, it is much more difficult to fix than with their beginning. Let's say you decide you want to move the functionality in your main () to another function. You may run into a real leak.

This is also a bad aesthetics, many developers will look at the loose "str" ​​and feel a slight nausea :(

+2
Mar 20 '13 at 8:17
source share

You have many answers to professional experience. Here I say a naive, but the answer, which I considered as a fact.

  • Summary

    3. Does it have deeper consequences?

    A: The answer will be in sufficient detail.

    2. Is it just good practice?

    A: This is considered good practice. Free up the resources / memory that you received when you are sure of it, are no longer used.

    • Why do I need to remove str if I finish the program anyway?
      I would not care if this memory goes to a land full of unicorns, if I'm just going to go out, right?

    A: you need or not need, in fact, you tell why. The following are some explanations.

    I think it depends. Here are some suggested questions; The term program can mean either an application or a function.

    Q: Does it depend on what the program does?

    A: If the destroyed universe was acceptable, then no. However, the program may not work as expected, and even be a program that does not do what it should. Can you seriously think about why you are building such a program?

    Q: Does it depend on how complicated the program is?

    A: No. See explanation.

    Q: Does the stability of the program depend on this?

    A: Close.

    And I believe that it depends

    • What is the universe of the program?
    • How was the program expected to do its job?
    • How much does the program cost for others, and the universe, where is it?

      For the term Universe, see Explanation.

    For a summary, it depends on what you care about .




  • Explanation

    Important: If we define the term program as a function, then its universe is an application. There are many details omitted; as an idea for understanding, this is long enough.

    We can ever see a diagram that illustrates the relationship between application software and system software.

    9RJKM.gif

    But in order to realize in what area of ​​coverage, I propose a reverse layout. Since we are only talking about software, the hardware level is omitted in the following diagram.

    mjLai.jpg

    In this diagram, we understand that the OS covers the largest area, which is the current universe, sometimes we talk about the environment. You can imagine that the whole architecture consists of a large number of disks, such as a diagram, to be either a cylinder or a torus (the ball is great, but it's hard to imagine). Here I should mention that most OSs are actually single, the runtime can be either single or multiple in different implementations.

    It is important that the runtime is responsive to both the OS and applications, but the latter is more important. Runtime is the application universe, if it destroys all the applications running under it, it has disappeared.

    Unlike humans on Earth, we live here, but we are not made up of the Earth; we will continue to live in other suitable conditions, if the time of the destruction of the Earth and we are not there.

    However, we can no longer exist when the universe is destroyed, because we live not only in the universe, but also from the universe.

    As mentioned above, the runtime is also responsible to the OS. the left circle in the following diagram looks like this.

    ScsZs.jpg

    This is basically like C program in OS. When the relationship between the application and the OS corresponds to this, this is the same situation as the runtime in the OS above. In this diagram, the OS is the application universe. The reason for using applications here should be related to the OS, because the OS cannot virtualize their code or is allowed to crash. If the OS always prevents them from doing this, then this is presumptuous, regardless of what the applications do. But think about drivers , this is one of the scenarios in which the OS should be broken, since such applications are considered as part of the OS .

    Finally, see the right circle in the diagram above. In this case, the application itself is a universe. Sometimes we call such an application operating system. If the OS has never allowed to download and run custom code, then it does everything itself. Even this allowed, after being completed, the memory goes nowhere , but the hardware . All exemption that may be required until its termination.

    So how much does your program care for others? How much does he care about his universe? And how was the program expected to do its job? It depends on what you care about .

+2
Mar 20 '13 at 9:33
source share

Why should I delete str if I am going to end a program?

Because you do not want to be lazy ...

I would not care if this memory goes to a land full of unicorns, if I'm just going to leave, right?

No, I don’t care about the land of unicorns. The land of Arwen is another matter. Then we could carve their horns and use them well (I heard that this is a good aphrodisiac).

Is this just good practice?

This is fairly good practice.

Does it have deeper consequences?

Someone else should cleanse you after. Maybe you like it, I went out from under the wings of my parents many years ago.

Place the while (1) loop construct around your code without deleting. Code complexity does not matter. Memory leaks are related to process time.

From a debugging point of view, not releasing system resources (file descriptors, etc.) can lead to more significant and difficult to find errors. Memory leaks while important are generally much easier to diagnose (why can't I write to this file?). Bad style will become a problem if you start working with threads.

 int main() { while(1) { char* str = new char[10]; for(int i=0;i<5;i++) { //Do stuff with str } } delete[] str; return 0; } 
+2
Mar 25 '13 at 16:22
source share

TECHNICAL , a programmer does not have to rely on the OS to do anything. Thus, the OS is not required to recover lost memory.

If you write code that deletes all of your dynamically allocated memory, then you will check the code in the future and let others use it in a larger project.

Source: Distribution and GC Myths (PostScript Alert!)

 Allocation Myth 4: Non-garbage-collected programs should always
 deallocate all memory they allocate.

 The Truth: Omitted deallocations in frequently executed code cause
 growing leaks.  They are rarely acceptable.  but Programs that retain
 most allocated memory until program exit often perform better without
 any intervening deallocation.  Malloc is much easier to implement if
 there is no free.

 In most cases, deallocating memory just before program exit is
 pointless.  The OS will reclaim it anyway.  Free will touch and page in
 the dead objects;  the OS won't.

 Consequence: Be careful with "leak detectors" that count allocations.
 Some "leaks" are good!
  • I find it very bad practice to use malloc / new without calling free / delete.

  • If the memory is still corrected, what harm can be a clear release when you need to?

  • Perhaps if the OS "restores" memory faster than for free, you will see increased performance; this method will not help you with any program that must remain running for a long period of time.

Having said that, I recommend you use the free / delete.




, , , ?




, , //. , . , 24x7. , - . , , . , - . . . .




Think about your class 'A' having to deconstruct. If you don't call
'delete' on 'a', that destructor won't get called. Usually, that won't
really matter if the process ends anyway. But what if the destructor
has to release eg objects in a database? Flush a cache to a logfile?
Write a memory cache back to disk? **You see, it not just 'good
practice' to delete objects, in some situations it is required**. 
+2
26 . '13 7:09
source share

, , , (, valgrind Coverity). , .

, . .

+2
27 . '13 19:29
source share

, ++, , - . - - ( , , ), - - ( , ) " ". , , , , . ...

+2
28 . '13 8:48
source share

, , , , , delete , ( ++) , . , , - .. , .

, , . , , , , , !

, ( ), , , !

, !

+1
30 . '13 6:52
source share



All Articles