Re: Vector reallocation

From: James Dennett (jdennett_at_acm.org)
Date: 07/26/04


Date: Mon, 26 Jul 2004 14:43:57 -0700

newbiecpp wrote:

> When you insert an element into a vector, if the internal memory is already
> used, how does the vector allocate additional memory? It just allocates one
> unit to satisfy the insert, or allocates a chunk of memory? I guss the
> vector will allocate a chunk of memory. If this is true, what algorithm
> does the vector use? How does vectors decide how big the chunk of memory to
> create?

The algorithm isn't specified by the C++ standard, so implementations
could vary.

As it happens, the performance (complexity) guarantees of the standard
essentially mandate (at least) exponential growth, so the many area of
difference is in the ratio: some std::vector implementations double
when they need to expand, some multiply their size by 1.5. Exponential
growth has the somewhat counter-intuitive property that when adding n
items to a vector, the number of copies needed grows only proportionally
to n: even though the number of copies at each expansion increases,
expansions become proportionally less common, so the two factors cancel
out nicely.

-- James



Relevant Pages

  • Linux 2.4: Allocation of >1GB in one chunk
    ... machine has 4GB memory and 4GB swap. ... is 1.3GB in one whole chunk. ... Will allocate 2621440000 bytes in 1MB chunks... ... unfortunately I don't know _where_ it fails. ...
    (Linux-Kernel)
  • Re: Reading from a file
    ... begin to read the files (and copy the contents to my array). ... If you do not know the file size ahead of time, you allocate memory ... the saved data into that big chunk, and then free the temporary copies. ...
    (comp.soft-sys.matlab)
  • Re: Dynamic memory in standard COBOL; using large data fields
    ... > not support the notion of dynamic memory. ... That is, there is no standard ... > malloc or calloc style keywords or calls I can make to allocate and grow ... > large chunk of memory that it only uses a fraction of normally. ...
    (comp.lang.cobol)
  • Re: brk vs mmap vs mmap2
    ... :you do a lot of little allocs and frees that you should allocate a bit ... :chunk of memory with the system call and then have your own memory ... :manager carve up that chunk into smaller pieces for the actual memory ... and will need additional dynamic allocations for player instances, ...
    (alt.lang.asm)
  • Re: Softkicking on a DKB Cobra/1240
    ... the KickMem and related list to allocate the memory at start up, ... memory, and coolcapture is delayed until after expansion has done its job. ... it contains later in a ColdCapture routine sitting in chip? ...
    (comp.sys.amiga.programmer)