1

I know that some part of the vector (the actual data) is stored in the heap, while some data (a struct containing the length, capacity and pointer to the actual data in heap) is stored on the stack.

What about a vector of vectors (i.e the elements of the vector are other vectors, e.g. a vector of strings)? What parts of this outer container vector are stored in the heap and on thee stack? What about the individual inner elements?

Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366

1 Answers1

4

It is not true that a Vec (the struct containing pointer, length and capacity) is always stored on the stack. You can move any type (excluding self-referential ones, which can't be moved) from the stack to the heap, by putting it in a Box, Vec or other heap-using smart pointer. Just consider a straightforward type like i64: it might be stored on the stack (or in a register if the compiler so chooses), but if you write vec![7i64], you have an i64 stored on the heap and the only thing left on the stack is the Vec itself (a pointer plus length and capacity).

With this analogy, it's not hard to see that the same applies for String: it can be on the stack, but you can put it on the heap by creating a Vec<String>. Therefore, if you have a Vec<String> with length 100, there are 101 independent heap allocations: one owned by the Vec and one owned by each of the Strings.

See also

Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366
trent
  • 25,033
  • 7
  • 51
  • 90
  • What do you mean by the "self referential" ones? – Satoshi Gekkouga Mar 03 '19 at 23:36
  • 1
    @Satoshi Values that contain a reference to themselves or part of themselves are "self-referential". These values cannot be moved because moving one to a different memory location could invalidate the reference. [This question](https://stackoverflow.com/q/32300132/3650362) has more information. – trent Mar 04 '19 at 00:28