Why do I need to delete[]?

前端 未结 15 668
猫巷女王i
猫巷女王i 2020-12-13 06:16

Lets 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
    }

    d         


        
15条回答
  •  生来不讨喜
    2020-12-13 06:34

    Why would I need to delete str if I am going to end the program anyways?

    Because you don't want to be lazy ...

    I wouldn't care if that memory goes to a land full of unicorns if I am just going to exit, right?

    Nope, I don't care about the land of unicorns either. The Land of Arwen is a different matter, Then we could cut their horns off and put them to good use(I've heard its a good aphrodisiac).

    Is it just good practice?

    It is justly a good practice.

    Does it have deeper consequences?

    Someone else has to clean up after you. Maybe you like that, I moved out from under my parents' roof many years ago.

    Place a while(1) loop construct around your code without delete. The code-complexity does not matter. Memory leaks are related to process time.

    From the perspective of debug, not releasing system resources(file handles, etc) can cause more significant and hard to find bugs. Memory-leaks while important are typically much easier to diagnose(why can't I write to this file?). Bad style will become more of 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;
    }
    

提交回复
热议问题