Thread: Memory reallocation

  1. #1
    Registered User
    Join Date
    Dec 2007
    Posts
    932

    Memory reallocation

    If I reallocate memory with 'new' it will erase what was written to the buffer but if I assign it to another pointer before reallocating, I can still print out what was there with the other pointer.
    How is that possible when the second pointer points to the same address as the first?

    Code:
    int main()
    {
        long iWholeSize = 17;
        char * buf = new (nothrow)char[iWholeSize];
        buf = "hello";
        char *pch = buf;
    
        buf = new (nothrow)char[iWholeSize+10];
    
        cout << "buf " << buf << "\n";
        cout << "pch " << pch << "\n";
    
        delete[] buf;
        return 0;
    }
    Using Windows 10 with Code Blocks and MingW.

  2. #2
    Hurry Slowly vart's Avatar
    Join Date
    Oct 2006
    Location
    Rishon LeZion, Israel
    Posts
    6,788
    Quote Originally Posted by Ducky View Post
    If I reallocate memory with 'new' it will erase what was written to the buffer
    It will not. you just replace you pointer value. but buffer still exists on the old address and the memory is "leaked" - since you have lost your access to it and have no way to free it.
    All problems in computer science can be solved by another level of indirection,
    except for the problem of too many layers of indirection.
    – David J. Wheeler

  3. #3
    Registered User
    Join Date
    Apr 2013
    Posts
    1,658
    This overwrites the pointer in buf:

    Code:
        buf = "hello";
    As far as I know, new does not reallocate memory. I get different addresses for buf and pch with this example:

    Code:
    int main()
    {
        long iWholeSize = 17;
        char * buf = new (nothrow)char[iWholeSize];
        strcpy(buf, "hello");
        char *pch = buf;
    
        buf = new (nothrow)char[iWholeSize+10];
        strcpy(buf, "world");
    
        cout << "pch " << pch << "\n";
        cout << "buf " << buf << "\n";
    
        delete[] buf;
        delete[] pch;
    
        return 0;
    }
    Last edited by rcgldr; 06-14-2013 at 10:08 AM.

  4. #4
    Master Apprentice phantomotap's Avatar
    Join Date
    Jan 2008
    Posts
    5,108
    O_o

    I just wanted to elaborate on what vart has already said.

    Code:
    int main()
    {
        long iWholeSize = 17;
        char * buf = new (nothrow)char[iWholeSize];
        buf = "hello"; // Leaks existing memory pointed to by `buf' without writing to the existing buf[n] because string literals don't work that way.
        char *pch = buf; // Simply creates a new pointer to the same memory without copying the memory pointed to by `buf' as pointers do not work that way.
     
        buf = new (nothrow)char[iWholeSize+10]; // Allocate memory without initializing the memory allocated to a known string.
     
        cout << "buf " << buf << "\n"; // You've told `cout' that `buf' is a null-terminated string, but you don't know what may be at the allocated memory.
        cout << "pch " << pch << "\n";
     
        delete[] buf;
        return 0;
    }

  5. #5
    Registered User
    Join Date
    Dec 2007
    Posts
    932
    Thank you.

    So should I delete[] buf the old pointer before reallocating it again?
    If I delete it it will crash when I reallocate it.
    Last edited by Ducky; 06-14-2013 at 10:10 AM.
    Using Windows 10 with Code Blocks and MingW.

  6. #6
    Registered User
    Join Date
    Apr 2013
    Posts
    1,658
    Quote Originally Posted by Ducky View Post
    So should I delete[] buf the old pointer before reallocating it again? If I delete it it will crash when I reallocate it.
    new does not reallocate, it just allocates a new block of memory. You should either copy buf to another pointer (which you can delete[] later) or delete [] buf before doing another new with buf. If you want to resize, use C++ string or vector.

  7. #7
    Registered User
    Join Date
    Dec 2007
    Posts
    932
    I can't use string or vector cause my function takes a pointer, is it good this way?
    Code:
    int main()
    {
        long iWholeSize = 17;
        char * buf = new (nothrow)char[iWholeSize];
        char pch[64];
        strcpy(pch, "hello");
    
        delete[] buf;
        buf = new (nothrow)char[iWholeSize+10];
    
        cout << "buf " << buf << "\n";
        cout << "pch " << pch << "\n";
    
        delete[] buf;
        return 0;
    }
    Using Windows 10 with Code Blocks and MingW.

  8. #8
    Master Apprentice phantomotap's Avatar
    Join Date
    Jan 2008
    Posts
    5,108
    I can't use string or vector cause my function takes a pointer, is it good this way?
    O_o

    The example is incomplete as examples often are in that you aren't checking for null, and it also still has the problem of initializing `buf' to a string before handing the memory to `cout'.

    You should check for `new' failing to allocate memory before you use it.

    You should force the memory allocated by `buf' to be a valid null-terminated string within the memory you've allocated (`buf[0] = 0;').

    Soma

  9. #9
    Registered User
    Join Date
    Apr 2013
    Posts
    1,658
    Quote Originally Posted by Ducky View Post
    I can't use string or vector cause my function takes a pointer, is it good this way? ... code example ...
    In your example, the program allocates buf, deletes buf, allocates buf, deletes buf, but never puts anything into buf.

  10. #10
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    28,413
    Quote Originally Posted by Ducky
    I can't use string or vector cause my function takes a pointer
    It may be possible that you can still use them, e.g.,
    Code:
    std::string buffer(iWholeSize);
    foo(&buffer[0]);
    Quote Originally Posted by Bjarne Stroustrup (2000-10-14)
    I get maybe two dozen requests for help with some sort of programming or design problem every day. Most have more sense than to send me hundreds of lines of code. If they do, I ask them to find the smallest example that exhibits the problem and send me that. Mostly, they then find the error themselves. "Finding the smallest program that demonstrates the error" is a powerful debugging tool.
    Look up a C++ Reference and learn How To Ask Questions The Smart Way

  11. #11
    Hurry Slowly vart's Avatar
    Join Date
    Oct 2006
    Location
    Rishon LeZion, Israel
    Posts
    6,788
    Quote Originally Posted by Ducky View Post
    I can't use string or vector cause my function takes a pointer,
    Still you can probably you std::string since it has a member c_str() which gives you a const pointer to c-style string contains in the object. and you can pass this pointer to your function. Of course your function should not try to modify contents of the pointer memory in this case
    All problems in computer science can be solved by another level of indirection,
    except for the problem of too many layers of indirection.
    – David J. Wheeler

  12. #12
    Hurry Slowly vart's Avatar
    Join Date
    Oct 2006
    Location
    Rishon LeZion, Israel
    Posts
    6,788
    Quote Originally Posted by laserlight View Post
    It may be possible that you can still use them, e.g.,
    Code:
    std::string buffer(iWholeSize);
    foo(&buffer[0]);
    I thought only std::vector guarantees that pointer to first element will point to continues memory?
    All problems in computer science can be solved by another level of indirection,
    except for the problem of too many layers of indirection.
    – David J. Wheeler

  13. #13
    Registered User
    Join Date
    Apr 2013
    Posts
    1,658
    Quote Originally Posted by Ducky View Post
    I can't use string or vector cause my function takes a pointer.
    You could actually use a pointer to string:

    Code:
    int main()
    {
        string * pstring = new string("init from cstring");
        cout << pstring->size() << ' ' << *pstring << endl;
        delete pstring;
        return 0;
    }

  14. #14
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    28,413
    Quote Originally Posted by vart
    I thought only std::vector guarantees that pointer to first element will point to continues memory?
    Changed for basic_string in C++11.

    Quote Originally Posted by rcgldr
    You could actually use a pointer to string:
    That would probably be pointless though
    Quote Originally Posted by Bjarne Stroustrup (2000-10-14)
    I get maybe two dozen requests for help with some sort of programming or design problem every day. Most have more sense than to send me hundreds of lines of code. If they do, I ask them to find the smallest example that exhibits the problem and send me that. Mostly, they then find the error themselves. "Finding the smallest program that demonstrates the error" is a powerful debugging tool.
    Look up a C++ Reference and learn How To Ask Questions The Smart Way

  15. #15
    Hurry Slowly vart's Avatar
    Join Date
    Oct 2006
    Location
    Rishon LeZion, Israel
    Posts
    6,788
    Quote Originally Posted by laserlight View Post
    Changed for basic_string in C++11.
    Good to know.
    But looks like it is supported only starting with MSVC2012... I'm still on 2008/2010 mostly. Ducky is also not there yet.
    All problems in computer science can be solved by another level of indirection,
    except for the problem of too many layers of indirection.
    – David J. Wheeler

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. reallocation of heap memory
    By sukhdeep in forum C++ Programming
    Replies: 17
    Last Post: 12-20-2011, 02:16 AM
  2. Reallocation of memory (3d dynamic matrix)
    By beta3designs in forum C Programming
    Replies: 13
    Last Post: 08-01-2011, 12:43 PM
  3. Memory allocation/reallocation
    By magda3227 in forum C Programming
    Replies: 10
    Last Post: 07-04-2008, 03:27 PM
  4. Memory reallocation in C++
    By spank in forum C++ Programming
    Replies: 2
    Last Post: 08-08-2007, 09:56 AM
  5. Dynamic memory reallocation
    By Gravedigga in forum C++ Programming
    Replies: 6
    Last Post: 05-15-2005, 06:39 PM