Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
633 views
in Technique[技术] by (71.8m points)

c++ - Is accessing the raw pointer after std::vector::reserve safe?

This is pretty farfetched, but is the following code "safe" (i.e. guaranteed not to cause segmentation fault):

std::vector<int> vec(1); // Ensures that &vec[0] is valid
vec.reserve(100);
memset(&vec[0], 0x123, sizeof(int)*100); // Safe?

I realize that this is ugly - I'm only interested to know if it's technically safe, not "pretty". I guess its only usage could be to ignore values stored beyond a given index.

Note! How can I get the address of the buffer allocated by vector::reserve()? covers the same topic, but I'm more interested if this is safe and if there are pitfalls doing this.

EDIT: Original code was wrong, replaced original memcpy with memset.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

No, it is not safe.

After a reserve(), the vector is guaranteed not to reallocate the storage until the capacity() is reached.

However, the standard doesn't say what the vector implementation can do with the storage between size() and capacity(). Perhaps it can be used for some internal data - who knows? Perhaps the address space is just reserved and not mapped to actual RAM?

Accessing elements outside of [0..size) is undefined behavior. There could be some hardware check for that.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...