Thread: Memory reallocation in C++

  1. #1
    Registered User
    Join Date
    Dec 2005
    Posts
    167

    Memory reallocation in C++

    I'm just starting to scratch the surface of c++. I want to know how can you realloc memory in C++. (It is like in C ? use realloc function ?)

    if i make:

    Code:
    int *x= new int[10];
    x=new int[20];
    it will keep the first values I enter?

  2. #2
    The larch
    Join Date
    May 2006
    Posts
    3,573
    You'll need to copy the original array over (to another new-ed memory) and free it.

    The snippet you have loses the contents of x and creates a memory leak, because you won't be able to delete the memory x pointed to before.

    Since all this needs a lot of work and is easy to mess up, many people use std::vector from C++ standard libraries when they need a dynamically resizing array.
    I might be wrong.

    Thank you, anon. You sure know how to recognize different types of trees from quite a long way away.
    Quoted more than 1000 times (I hope).

  3. #3
    System Novice siavoshkc's Avatar
    Join Date
    Jan 2006
    Location
    Tehran
    Posts
    1,246
    We recently had a thread on it.
    Learn C++ (C++ Books, C Books, FAQ, Forum Search)
    Code painter latest version on sourceforge DOWNLOAD NOW!
    Download FSB Data Integrity Tester.
    Siavosh K C

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Problems with shared memory shmdt() shmctl()
    By Jcarroll in forum C Programming
    Replies: 1
    Last Post: 03-17-2009, 10:48 PM
  2. Question regarding Memory Leak
    By clegs in forum C++ Programming
    Replies: 29
    Last Post: 12-07-2007, 01:57 AM
  3. Memory problem with Borland C 3.1
    By AZ1699 in forum C Programming
    Replies: 16
    Last Post: 11-16-2007, 11:22 AM
  4. Shared Memory - shmget questions
    By hendler in forum C Programming
    Replies: 1
    Last Post: 11-29-2005, 02:15 AM
  5. Understanding Memory Allocation
    By Ragsdale85 in forum C Programming
    Replies: 7
    Last Post: 10-31-2005, 08:36 AM