Memory reallocation in C++

This is a discussion on Memory reallocation in C++ within the C++ Programming forums, part of the General Programming Boards category; I'm just starting to scratch the surface of c++. I want to know how can you realloc memory 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,231
    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, 12:57 AM
  3. Memory problem with Borland C 3.1
    By AZ1699 in forum C Programming
    Replies: 16
    Last Post: 11-16-2007, 10:22 AM
  4. Shared Memory - shmget questions
    By hendler in forum C Programming
    Replies: 1
    Last Post: 11-29-2005, 01:15 AM
  5. Understanding Memory Allocation
    By Ragsdale85 in forum C Programming
    Replies: 7
    Last Post: 10-31-2005, 07:36 AM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21