0

Is there any possible undefined behaviour if I use std::string to store any bytes like using a std::vector?

Zz Tux
  • 600
  • 1
  • 5
  • 18
  • 2
    The only possible issue is that `char` is potentially a signed quantity and bytes are often thought of as unsigned. Apart from that there are no issues. But you should ask yourself what is the benefit of `std::string` over `std::vector` – john Apr 15 '23 at 06:10
  • In general you should be fine. But in theory UB is almost always possible like std::string::data() gives you a pointer that you can dereference out of range. – Pepijn Kramer Apr 15 '23 at 06:11
  • UB, unlikely. But it can lead people to misuse and misunderstand the code. – ALX23z Apr 15 '23 at 06:11
  • 1
    Sure, you can abuse `std::string` to store `char`s instead of vectors, but in my mind, it doesn't make sense to store anything other than printable characters in a `std::string`. Whenever I see `std::string`, I think there's a general assumption made that whatever is in there can be seen, and if it can't, there's a problem. – fireshadow52 Apr 15 '23 at 06:14
  • Can you give us some more context: why do you want/need to do this ? – wohlstad Apr 15 '23 at 06:51
  • As long as you use your collection to store bytes in, there will be no undefined behavior. But if you used other string abilities, then you will have undefined behaviors; for examples, 0x00 has a special meaning, `end()` can be dereferenced... So if you need to use a byte array, **using `vector` is much less risky than `string`**. – dalfaB Apr 15 '23 at 08:45
  • 1
    @dalfaB *"if you used other string abilities, then you will have undefined behaviors"* Can you be more specific? Embedded nulls shouldn't cause UB. – HolyBlackCat Apr 15 '23 at 10:40
  • @HolyBlackCat, I agree, the examples I've given do not made directly UBs. The idea is when is std::string we may be tempted of using string capacities, like c_str() and then the presence of null characters will give unexpected results. So I agree this is not UB. – dalfaB Apr 15 '23 at 17:04

0 Answers0