Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

With the memory changes the UB surface of String(Vector{UInt8}) is larger #54434

Open
gbaraldi opened this issue May 10, 2024 · 1 comment
Open
Labels
domain:arrays [a, r, r, a, y, s] domain:strings "Strings!"

Comments

@gbaraldi
Copy link
Member

Observing/modifying the data of a Vector{UInt8} after one has called String(vec) on it has always been UB, this was usually fine because it's quite hard on a pre-Memory{T} world to have two arrays alias eachother while not being ===, this is no longer true with Memory, where one can still keep that Memory around and have it be shared by the string, which can make it possible to mutate it, causing UB.

One option woul to have String(vec) now make a copy and create something like unsafe_take! or similar like suggested in #54424 which makes it clear that this is a potentially unsafe function.

@jakobnissen
Copy link
Contributor

jakobnissen commented May 13, 2024

I think it's pretty hard to accidentally cause UB with the current implementation, because as far as I can tell String(::Vector{UInt8}) will copy, unless the backing memory has been allocated using the internal Base.StringVector or Base.StringMemory methods.
Maybe in the future, String(::Vector{UInt8}) will be zero-copy for normal arrays in which case this is indeed a problem, but that is not now:

julia> v1 = zeros(UInt8, 3)
       v2 = view(v1.ref.mem, 1:3)
       s = String(v1)
       v2[1] = 0xff
       s
"\0\0\0"

Edit: I see that IOBuffer uses StringMemory internally...

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
domain:arrays [a, r, r, a, y, s] domain:strings "Strings!"
Projects
None yet
Development

No branches or pull requests

4 participants