Memory leaking with memory allocationc++ <error: Cannot access memory at address 0x1>Activity has leaked window that was originally addedC++11 introduced a standardized memory model. What does it mean? And how is it going to affect C++ programming?Creating a memory leak with JavaWhy should C++ programmers minimize use of 'new'?performSelector may cause a leak because its selector is unknownMemory leaks with alloc in Objective-CPossible to manually leak memory?Does deleting dynamically allocated std::string using a pointer returned by c_str() cause a memory leak in C++?Deallocating memory to avoid memory leaksReplacing a 32-bit loop counter with 64-bit introduces crazy performance deviations

How is the claim "I am in New York only if I am in America" the same as "If I am in New York, then I am in America?

What are these boxed doors outside store fronts in New York?

What is the command to reset a PC without deleting any files

Can an x86 CPU running in real mode be considered to be basically an 8086 CPU?

Can a German sentence have two subjects?

My colleague's body is amazing

Schwarzchild Radius of the Universe

Should I join an office cleaning event for free?

The use of multiple foreign keys on same column in SQL Server

Is it possible to do 50 km distance without any previous training?

Circuitry of TV splitters

How do we improve the relationship with a client software team that performs poorly and is becoming less collaborative?

Are white and non-white police officers equally likely to kill black suspects?

I’m planning on buying a laser printer but concerned about the life cycle of toner in the machine

Infinite past with a beginning?

If Manufacturer spice model and Datasheet give different values which should I use?

Patience, young "Padovan"

What would happen to a modern skyscraper if it rains micro blackholes?

Copycat chess is back

Chess with symmetric move-square

Do airline pilots ever risk not hearing communication directed to them specifically, from traffic controllers?

"which" command doesn't work / path of Safari?

A Journey Through Space and Time

Calculus Optimization - Point on graph closest to given point



Memory leaking with memory allocation


c++ <error: Cannot access memory at address 0x1>Activity has leaked window that was originally addedC++11 introduced a standardized memory model. What does it mean? And how is it going to affect C++ programming?Creating a memory leak with JavaWhy should C++ programmers minimize use of 'new'?performSelector may cause a leak because its selector is unknownMemory leaks with alloc in Objective-CPossible to manually leak memory?Does deleting dynamically allocated std::string using a pointer returned by c_str() cause a memory leak in C++?Deallocating memory to avoid memory leaksReplacing a 32-bit loop counter with 64-bit introduces crazy performance deviations






.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty height:90px;width:728px;box-sizing:border-box;








4















c++ <error: Cannot access memory at address 0x1>

I have an additional question about this question.
The answerer said that the first one



des = new char[src.size() + 1];


will cause memory leaking since des is a local variable so he suggested another method right after.



char* toNormalWord(const std::string& src)

char* des = new char[src.size() + 1];
// stuff
return des;



But I can't understand why the local variable will cause memory leaking and what is the difference between the first one and the second one.
Isn’t the second one also using des as a local variable in the function?
I thought the difference was just that the function receives des as a parameter or just creates themselves.
I think I don't know something important but I don't know what that is...










share|improve this question






















  • Where is your call to delete [] the memory? It is the lack of using delete [] at some point in the code that causes the memory leak. Take the advice of the answer given at the link -- use std::string.

    – PaulMcKenzie
    Mar 22 at 1:12


















4















c++ <error: Cannot access memory at address 0x1>

I have an additional question about this question.
The answerer said that the first one



des = new char[src.size() + 1];


will cause memory leaking since des is a local variable so he suggested another method right after.



char* toNormalWord(const std::string& src)

char* des = new char[src.size() + 1];
// stuff
return des;



But I can't understand why the local variable will cause memory leaking and what is the difference between the first one and the second one.
Isn’t the second one also using des as a local variable in the function?
I thought the difference was just that the function receives des as a parameter or just creates themselves.
I think I don't know something important but I don't know what that is...










share|improve this question






















  • Where is your call to delete [] the memory? It is the lack of using delete [] at some point in the code that causes the memory leak. Take the advice of the answer given at the link -- use std::string.

    – PaulMcKenzie
    Mar 22 at 1:12














4












4








4








c++ <error: Cannot access memory at address 0x1>

I have an additional question about this question.
The answerer said that the first one



des = new char[src.size() + 1];


will cause memory leaking since des is a local variable so he suggested another method right after.



char* toNormalWord(const std::string& src)

char* des = new char[src.size() + 1];
// stuff
return des;



But I can't understand why the local variable will cause memory leaking and what is the difference between the first one and the second one.
Isn’t the second one also using des as a local variable in the function?
I thought the difference was just that the function receives des as a parameter or just creates themselves.
I think I don't know something important but I don't know what that is...










share|improve this question














c++ <error: Cannot access memory at address 0x1>

I have an additional question about this question.
The answerer said that the first one



des = new char[src.size() + 1];


will cause memory leaking since des is a local variable so he suggested another method right after.



char* toNormalWord(const std::string& src)

char* des = new char[src.size() + 1];
// stuff
return des;



But I can't understand why the local variable will cause memory leaking and what is the difference between the first one and the second one.
Isn’t the second one also using des as a local variable in the function?
I thought the difference was just that the function receives des as a parameter or just creates themselves.
I think I don't know something important but I don't know what that is...







c++ dynamic memory-leaks






share|improve this question













share|improve this question











share|improve this question




share|improve this question










asked Mar 22 at 0:59









Thank you for answeringThank you for answering

386




386












  • Where is your call to delete [] the memory? It is the lack of using delete [] at some point in the code that causes the memory leak. Take the advice of the answer given at the link -- use std::string.

    – PaulMcKenzie
    Mar 22 at 1:12


















  • Where is your call to delete [] the memory? It is the lack of using delete [] at some point in the code that causes the memory leak. Take the advice of the answer given at the link -- use std::string.

    – PaulMcKenzie
    Mar 22 at 1:12

















Where is your call to delete [] the memory? It is the lack of using delete [] at some point in the code that causes the memory leak. Take the advice of the answer given at the link -- use std::string.

– PaulMcKenzie
Mar 22 at 1:12






Where is your call to delete [] the memory? It is the lack of using delete [] at some point in the code that causes the memory leak. Take the advice of the answer given at the link -- use std::string.

– PaulMcKenzie
Mar 22 at 1:12













3 Answers
3






active

oldest

votes


















2














To understand the meaning of the sentence fragment "will just leak memory, since des is a local variable", one must understand the context. What was not said explicitly is that the value of the local variable was in no way copied elsewhere.



If the value is lost, then allocation is leaked.




what is the difference between the first one and the second one.




When the value assigned here: des = new char[src.size() + 1]; is not communicated to the outside of the function, the allocation will unconditionally leak at the end of the function.



When the value is returned, it can potentially be deleted later, thereby avoiding the leak.




Isn’t the second one also using des as a local variable in the function?




Yes. The difference is in whether its value is returned or not.






share|improve this answer























  • Thank you so much!! I should study much more

    – Thank you for answering
    Mar 23 at 4:54


















0














first, des is local variable but it is pointer variable and you allocate (src.size() + 1) size memory so it allocated in heap memory in your process.



check this web site



http://www.cplusplus.com/doc/tutorial/dynamic/






share|improve this answer






























    0














    eerorika answer is correct, but can be expanded.



    Then memory is allocated locally then this function responsibility is to deallocate it.
    If you return it then you push this responsibility on someone else and this is dangerous. You will have same problem like in your function but in other place:



    char* toNormalWord(const std::string& src);

    void processString(const std::string& src)

    char* des = toNormalWord(src);
    /* ... */
    if (c == 'n') throw new std::exception("invalid character!"); //memory leak of `des`!
    /* ... */
    return; //memory leak of `des`!



    Now your memory is now local to other function and it should be free there.



    Probably best way to avoid all this is use std::unique_ptr<char[]>:



    std::unique_ptr<char[]> toNormalWord(const std::string& src)

    std::unique_ptr<char[]> des(new char[src.size() + 1]);
    /* ... */
    return des;


    void processString(const std::string& src)

    std::unique_ptr<char[]> des = toNormalWord(src);
    /* ... */
    if (c == 'n') throw new std::exception("invalid character!"); //no memory leak!
    /* ... */
    return; //no memory leak!



    with this compiler will always remember to free this memory.



    In this specific case you can use std::string as suggested by barry. In some cases I even used std::vecotr for strings. All this depend on what usage of this "memory" is.
    std::string is best when you need do a lot of string operations like concatenation.






    share|improve this answer























    • Wow, thank you it helped a lot

      – Thank you for answering
      Mar 23 at 4:56











    Your Answer






    StackExchange.ifUsing("editor", function ()
    StackExchange.using("externalEditor", function ()
    StackExchange.using("snippets", function ()
    StackExchange.snippets.init();
    );
    );
    , "code-snippets");

    StackExchange.ready(function()
    var channelOptions =
    tags: "".split(" "),
    id: "1"
    ;
    initTagRenderer("".split(" "), "".split(" "), channelOptions);

    StackExchange.using("externalEditor", function()
    // Have to fire editor after snippets, if snippets enabled
    if (StackExchange.settings.snippets.snippetsEnabled)
    StackExchange.using("snippets", function()
    createEditor();
    );

    else
    createEditor();

    );

    function createEditor()
    StackExchange.prepareEditor(
    heartbeatType: 'answer',
    autoActivateHeartbeat: false,
    convertImagesToLinks: true,
    noModals: true,
    showLowRepImageUploadWarning: true,
    reputationToPostImages: 10,
    bindNavPrevention: true,
    postfix: "",
    imageUploader:
    brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
    contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
    allowUrls: true
    ,
    onDemand: true,
    discardSelector: ".discard-answer"
    ,immediatelyShowMarkdownHelp:true
    );



    );













    draft saved

    draft discarded


















    StackExchange.ready(
    function ()
    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55291405%2fmemory-leaking-with-memory-allocation%23new-answer', 'question_page');

    );

    Post as a guest















    Required, but never shown

























    3 Answers
    3






    active

    oldest

    votes








    3 Answers
    3






    active

    oldest

    votes









    active

    oldest

    votes






    active

    oldest

    votes









    2














    To understand the meaning of the sentence fragment "will just leak memory, since des is a local variable", one must understand the context. What was not said explicitly is that the value of the local variable was in no way copied elsewhere.



    If the value is lost, then allocation is leaked.




    what is the difference between the first one and the second one.




    When the value assigned here: des = new char[src.size() + 1]; is not communicated to the outside of the function, the allocation will unconditionally leak at the end of the function.



    When the value is returned, it can potentially be deleted later, thereby avoiding the leak.




    Isn’t the second one also using des as a local variable in the function?




    Yes. The difference is in whether its value is returned or not.






    share|improve this answer























    • Thank you so much!! I should study much more

      – Thank you for answering
      Mar 23 at 4:54















    2














    To understand the meaning of the sentence fragment "will just leak memory, since des is a local variable", one must understand the context. What was not said explicitly is that the value of the local variable was in no way copied elsewhere.



    If the value is lost, then allocation is leaked.




    what is the difference between the first one and the second one.




    When the value assigned here: des = new char[src.size() + 1]; is not communicated to the outside of the function, the allocation will unconditionally leak at the end of the function.



    When the value is returned, it can potentially be deleted later, thereby avoiding the leak.




    Isn’t the second one also using des as a local variable in the function?




    Yes. The difference is in whether its value is returned or not.






    share|improve this answer























    • Thank you so much!! I should study much more

      – Thank you for answering
      Mar 23 at 4:54













    2












    2








    2







    To understand the meaning of the sentence fragment "will just leak memory, since des is a local variable", one must understand the context. What was not said explicitly is that the value of the local variable was in no way copied elsewhere.



    If the value is lost, then allocation is leaked.




    what is the difference between the first one and the second one.




    When the value assigned here: des = new char[src.size() + 1]; is not communicated to the outside of the function, the allocation will unconditionally leak at the end of the function.



    When the value is returned, it can potentially be deleted later, thereby avoiding the leak.




    Isn’t the second one also using des as a local variable in the function?




    Yes. The difference is in whether its value is returned or not.






    share|improve this answer













    To understand the meaning of the sentence fragment "will just leak memory, since des is a local variable", one must understand the context. What was not said explicitly is that the value of the local variable was in no way copied elsewhere.



    If the value is lost, then allocation is leaked.




    what is the difference between the first one and the second one.




    When the value assigned here: des = new char[src.size() + 1]; is not communicated to the outside of the function, the allocation will unconditionally leak at the end of the function.



    When the value is returned, it can potentially be deleted later, thereby avoiding the leak.




    Isn’t the second one also using des as a local variable in the function?




    Yes. The difference is in whether its value is returned or not.







    share|improve this answer












    share|improve this answer



    share|improve this answer










    answered Mar 22 at 1:25









    eerorikaeerorika

    89.4k664136




    89.4k664136












    • Thank you so much!! I should study much more

      – Thank you for answering
      Mar 23 at 4:54

















    • Thank you so much!! I should study much more

      – Thank you for answering
      Mar 23 at 4:54
















    Thank you so much!! I should study much more

    – Thank you for answering
    Mar 23 at 4:54





    Thank you so much!! I should study much more

    – Thank you for answering
    Mar 23 at 4:54













    0














    first, des is local variable but it is pointer variable and you allocate (src.size() + 1) size memory so it allocated in heap memory in your process.



    check this web site



    http://www.cplusplus.com/doc/tutorial/dynamic/






    share|improve this answer



























      0














      first, des is local variable but it is pointer variable and you allocate (src.size() + 1) size memory so it allocated in heap memory in your process.



      check this web site



      http://www.cplusplus.com/doc/tutorial/dynamic/






      share|improve this answer

























        0












        0








        0







        first, des is local variable but it is pointer variable and you allocate (src.size() + 1) size memory so it allocated in heap memory in your process.



        check this web site



        http://www.cplusplus.com/doc/tutorial/dynamic/






        share|improve this answer













        first, des is local variable but it is pointer variable and you allocate (src.size() + 1) size memory so it allocated in heap memory in your process.



        check this web site



        http://www.cplusplus.com/doc/tutorial/dynamic/







        share|improve this answer












        share|improve this answer



        share|improve this answer










        answered Mar 22 at 1:05









        Seil ChoiSeil Choi

        324




        324





















            0














            eerorika answer is correct, but can be expanded.



            Then memory is allocated locally then this function responsibility is to deallocate it.
            If you return it then you push this responsibility on someone else and this is dangerous. You will have same problem like in your function but in other place:



            char* toNormalWord(const std::string& src);

            void processString(const std::string& src)

            char* des = toNormalWord(src);
            /* ... */
            if (c == 'n') throw new std::exception("invalid character!"); //memory leak of `des`!
            /* ... */
            return; //memory leak of `des`!



            Now your memory is now local to other function and it should be free there.



            Probably best way to avoid all this is use std::unique_ptr<char[]>:



            std::unique_ptr<char[]> toNormalWord(const std::string& src)

            std::unique_ptr<char[]> des(new char[src.size() + 1]);
            /* ... */
            return des;


            void processString(const std::string& src)

            std::unique_ptr<char[]> des = toNormalWord(src);
            /* ... */
            if (c == 'n') throw new std::exception("invalid character!"); //no memory leak!
            /* ... */
            return; //no memory leak!



            with this compiler will always remember to free this memory.



            In this specific case you can use std::string as suggested by barry. In some cases I even used std::vecotr for strings. All this depend on what usage of this "memory" is.
            std::string is best when you need do a lot of string operations like concatenation.






            share|improve this answer























            • Wow, thank you it helped a lot

              – Thank you for answering
              Mar 23 at 4:56















            0














            eerorika answer is correct, but can be expanded.



            Then memory is allocated locally then this function responsibility is to deallocate it.
            If you return it then you push this responsibility on someone else and this is dangerous. You will have same problem like in your function but in other place:



            char* toNormalWord(const std::string& src);

            void processString(const std::string& src)

            char* des = toNormalWord(src);
            /* ... */
            if (c == 'n') throw new std::exception("invalid character!"); //memory leak of `des`!
            /* ... */
            return; //memory leak of `des`!



            Now your memory is now local to other function and it should be free there.



            Probably best way to avoid all this is use std::unique_ptr<char[]>:



            std::unique_ptr<char[]> toNormalWord(const std::string& src)

            std::unique_ptr<char[]> des(new char[src.size() + 1]);
            /* ... */
            return des;


            void processString(const std::string& src)

            std::unique_ptr<char[]> des = toNormalWord(src);
            /* ... */
            if (c == 'n') throw new std::exception("invalid character!"); //no memory leak!
            /* ... */
            return; //no memory leak!



            with this compiler will always remember to free this memory.



            In this specific case you can use std::string as suggested by barry. In some cases I even used std::vecotr for strings. All this depend on what usage of this "memory" is.
            std::string is best when you need do a lot of string operations like concatenation.






            share|improve this answer























            • Wow, thank you it helped a lot

              – Thank you for answering
              Mar 23 at 4:56













            0












            0








            0







            eerorika answer is correct, but can be expanded.



            Then memory is allocated locally then this function responsibility is to deallocate it.
            If you return it then you push this responsibility on someone else and this is dangerous. You will have same problem like in your function but in other place:



            char* toNormalWord(const std::string& src);

            void processString(const std::string& src)

            char* des = toNormalWord(src);
            /* ... */
            if (c == 'n') throw new std::exception("invalid character!"); //memory leak of `des`!
            /* ... */
            return; //memory leak of `des`!



            Now your memory is now local to other function and it should be free there.



            Probably best way to avoid all this is use std::unique_ptr<char[]>:



            std::unique_ptr<char[]> toNormalWord(const std::string& src)

            std::unique_ptr<char[]> des(new char[src.size() + 1]);
            /* ... */
            return des;


            void processString(const std::string& src)

            std::unique_ptr<char[]> des = toNormalWord(src);
            /* ... */
            if (c == 'n') throw new std::exception("invalid character!"); //no memory leak!
            /* ... */
            return; //no memory leak!



            with this compiler will always remember to free this memory.



            In this specific case you can use std::string as suggested by barry. In some cases I even used std::vecotr for strings. All this depend on what usage of this "memory" is.
            std::string is best when you need do a lot of string operations like concatenation.






            share|improve this answer













            eerorika answer is correct, but can be expanded.



            Then memory is allocated locally then this function responsibility is to deallocate it.
            If you return it then you push this responsibility on someone else and this is dangerous. You will have same problem like in your function but in other place:



            char* toNormalWord(const std::string& src);

            void processString(const std::string& src)

            char* des = toNormalWord(src);
            /* ... */
            if (c == 'n') throw new std::exception("invalid character!"); //memory leak of `des`!
            /* ... */
            return; //memory leak of `des`!



            Now your memory is now local to other function and it should be free there.



            Probably best way to avoid all this is use std::unique_ptr<char[]>:



            std::unique_ptr<char[]> toNormalWord(const std::string& src)

            std::unique_ptr<char[]> des(new char[src.size() + 1]);
            /* ... */
            return des;


            void processString(const std::string& src)

            std::unique_ptr<char[]> des = toNormalWord(src);
            /* ... */
            if (c == 'n') throw new std::exception("invalid character!"); //no memory leak!
            /* ... */
            return; //no memory leak!



            with this compiler will always remember to free this memory.



            In this specific case you can use std::string as suggested by barry. In some cases I even used std::vecotr for strings. All this depend on what usage of this "memory" is.
            std::string is best when you need do a lot of string operations like concatenation.







            share|improve this answer












            share|improve this answer



            share|improve this answer










            answered Mar 22 at 11:11









            YankesYankes

            1,2621111




            1,2621111












            • Wow, thank you it helped a lot

              – Thank you for answering
              Mar 23 at 4:56

















            • Wow, thank you it helped a lot

              – Thank you for answering
              Mar 23 at 4:56
















            Wow, thank you it helped a lot

            – Thank you for answering
            Mar 23 at 4:56





            Wow, thank you it helped a lot

            – Thank you for answering
            Mar 23 at 4:56

















            draft saved

            draft discarded
















































            Thanks for contributing an answer to Stack Overflow!


            • Please be sure to answer the question. Provide details and share your research!

            But avoid


            • Asking for help, clarification, or responding to other answers.

            • Making statements based on opinion; back them up with references or personal experience.

            To learn more, see our tips on writing great answers.




            draft saved


            draft discarded














            StackExchange.ready(
            function ()
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55291405%2fmemory-leaking-with-memory-allocation%23new-answer', 'question_page');

            );

            Post as a guest















            Required, but never shown





















































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown

































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown







            Popular posts from this blog

            Kamusi Yaliyomo Aina za kamusi | Muundo wa kamusi | Faida za kamusi | Dhima ya picha katika kamusi | Marejeo | Tazama pia | Viungo vya nje | UrambazajiKuhusu kamusiGo-SwahiliWiki-KamusiKamusi ya Kiswahili na Kiingerezakuihariri na kuongeza habari

            Swift 4 - func physicsWorld not invoked on collision? The Next CEO of Stack OverflowHow to call Objective-C code from Swift#ifdef replacement in the Swift language@selector() in Swift?#pragma mark in Swift?Swift for loop: for index, element in array?dispatch_after - GCD in Swift?Swift Beta performance: sorting arraysSplit a String into an array in Swift?The use of Swift 3 @objc inference in Swift 4 mode is deprecated?How to optimize UITableViewCell, because my UITableView lags

            Access current req object everywhere in Node.js ExpressWhy are global variables considered bad practice? (node.js)Using req & res across functionsHow do I get the path to the current script with Node.js?What is Node.js' Connect, Express and “middleware”?Node.js w/ express error handling in callbackHow to access the GET parameters after “?” in Express?Modify Node.js req object parametersAccess “app” variable inside of ExpressJS/ConnectJS middleware?Node.js Express app - request objectAngular Http Module considered middleware?Session variables in ExpressJSAdd properties to the req object in expressjs with Typescript