3 ms·
> # Undefined behaviour > "abc" at 0 = 'd' Why is this undefined? Because the string literal is read-only?
by adastra22 3y ago
> # Undefined behaviour
> "abc" at 0 = 'd'
Why is this undefined? Because the string literal is read-only?
- astrobe_ 3y agoMaybe indexing starts at 1 ?
- astrobe_ 3y agoOh, my bad. I confused somehow the assignment for an equality test.
- anilakar 3y agoThey are apparantly allocated in a non-writable section. Non-const qualified string literals cannot* be modified in C either. The following snippet will cause a segfault: int main(void) { char *s = "abc"; s[0] = 'd'; puts(s); } *) At least in any environment I'm aware of. If you know one where they are, let me know.
- flohofwoe 3y ago...not in WASM (running in browsers at least, other WASM runtimes might implement the WASM heap differently and allow write-protected pages). PS: FWIW, wasmtime happily runs the code: wasmtime bla.wasm dbc
- Smaug123 3y ago(Of course, since this is undefined behaviour - https://www.open-std.org/jtc1/sc22/wg14/www/docs/n1570.pdf https://www.open-std.org/jtc1/sc22/wg14/www/docs/n1570.pdf , section 6.4.5 para 7 - literally any behaviour from any implementation is perfectly compliant.)
- flohofwoe 3y agoMy guess is that the actual behaviour depends on the runtime environment. On some platforms you might get a segfault, on others it might overwrite the first character.
- adastra22 3y agoYeah I think this is the answer. Maybe it should be obvious, but I had to think it through. Maybe not the best example for the first-exposure documentation in the README?