Value of the *ptr in the String of capacity 0

Hello, I was wondering does preforming String::new() actually result in any heap allocation? I assume it wouldn't as that would imply we are allocating 0 bytes on the heap which at least to me is a little weird. But I was wondering that if it isn't the case what would be the value of the pointer in a String in that case, and how would we get that value?

It doesn't, as described in the documentation of String::new:

Given that the String is empty, this will not allocate any initial buffer. While that means that this initial operation is very inexpensive, it may cause excessive allocation later when you add data.

I think that's not specified, i.e. it can be anything in the case of an empty string. You can get the pointer using String::as_ptr.

2 Likes

Thanks ngl, posted this question mostly for it to be more index-able as I feel this is something that new people might be asking themselfs.
I did a bit more digging under the hood String is Vec, and Vec is RawVec. And as stated in RawVec::new()

Creates a new RawVec of capacity 0 and a dangling pointer. No allocation is performed.

Further down in the implementation it is shown that the pointer value is acquired using NonNull::dangling()

1 Like

The lack of allocation is a documented guarantee. But that[1] is an implementation detail, which is not guaranteed to stay the way it is today.


  1. and all of RawVec â†Šī¸Ž

2 Likes

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.