CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 5 of 5

Thread: Memory problem

  1. #1
    Join Date
    May 2002
    Location
    Mumbai
    Posts
    197

    Memory problem

    What is the significance of memory in the following code:
    consider function
    // code begin
    char* ReturnDup(const char* pChOrg)
    {
    char* pChDup;
    pChDup = new char[strlen(pChOrg)+1];
    strcpy(pChDup,pChOrg);
    return pChDup;
    }
    // code over
    suppose main program uses this function, like
    // code begin
    ...
    ...
    char* pChFun;
    pChFun = ReturnDup("Life is wonderful");
    cout << pChFun << endl;
    ...
    ...
    ...
    // code over
    what ever memory we have allocated is in function ReturnDup, doesnt it remain local in the function ReturnDup?
    how can we use the return value in main()?....

  2. #2
    Join Date
    Jun 2001
    Location
    Switzerland
    Posts
    4,443
    No, it doesn't. The char * pChDup is a local variable. It will be destroyed when the function exits but the memory it points to will remain allocated until you delete[] it.
    (ok, a char * is a built in, it does not have a dtor -- the term "destroyed" may be inappropiate).
    Gabriel, CodeGuru moderator

    Forever trusting who we are
    And nothing else matters
    - Metallica

    Learn about the advantages of std::vector.

  3. #3
    Join Date
    Mar 2003
    Location
    China
    Posts
    10
    Sure, the char *pChDup is destroyed when ReturnDub exits, but you may still use the memory it was pointed to freely.

  4. #4
    Join Date
    May 2002
    Location
    Ukraine
    Posts
    228
    You can use memmory, becouse
    return pChDup;
    create copy of pChDup for returning from
    function before pChDup local pointer will be destroed.

  5. #5
    Join Date
    Mar 2003
    Posts
    6
    Sunny,

    Variables declared locally, such as
    int x; string MyString;
    -- these are deleted when they go out of scope, such as when the function returns.
    These are put on the stack, and are fast.

    However, memory *allocated* using new and delete are NOT deleted when the go out of scope. For example, the program

    int main()
    {
    char * mine;
    mine = new char[500];
    }

    creates a memory leak, because the memory allocated is never deleted.
    Memory allocated with new stays good until it's deleted, so it can be used anywhere in the program as long as you have the pointer to it.

    Does this help at all?

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  





Click Here to Expand Forum to Full Width

Featured