Bug 24355 – Slice copy with static arrays incorrect bounds checking

Status
NEW
Severity
normal
Priority
P1
Component
dmd
Product
D
Version
D2
Platform
x86_64
OS
All
Creation time
2024-01-25T19:43:57Z
Last change time
2024-12-13T19:32:47Z
Assigned to
No Owner
Creator
ryuukk_
Moved to GitHub: dmd#20388 →

Comments

Comment #0 by ryuukk.dev — 2024-01-25T19:43:57Z
## Case 1: ``` void main() { char[32] id = 0; const(char)* str = "hello"; id = str[0 .. 6]; } ``` id is large enough for the string "hello", it should compile instead i get: `` Error: mismatched array lengths 32 and 6 for assignment `id[] = str[0..6] `` ## Case 2: ``` void main() { char[4] id; id = "hello asdad"; } ``` is not not large enough, both string and array length are known at compile time, this shouldn't compile error should be: `` Error: mismatched array lengths 4 and 1 for assignment `id[] = "hello asdad" ``
Comment #1 by dfj1esp02 — 2024-01-25T20:02:42Z
In case 1 it's unclear what you want, it can be id[0..6]=str[0..6] or id[0..6]=str[0..6],id[6..12]=str[0..6],... - pattern copy.
Comment #2 by ryuukk.dev — 2024-01-25T20:51:18Z
I expect the same as: ``` void main() { char[32] id = "hello"; } ``` left: static array right: slice result: slice -> copy -> [0 .. slice.length]
Comment #3 by nick — 2024-01-26T12:44:18Z
char[32] id = 0; const(char)* str = "hello"; id = str[0 .. 6]; The error is correct by the spec: > A static array can be assigned from a dynamic array - the data is copied. The lengths must match https://dlang.org/spec/arrays.html#assignment char[4] id; id = "hello asdad"; This causes a runtime error. You're right it could be caught at compile-time. Assigning an array literal with excess elements is a compile error. char[32] id = "hello"; An array *initializer* is allowed to have fewer elements. If there are excess elements, for an array literal it's a compile error, for a string literal, it's a runtime error as above.
Comment #4 by nick — 2024-01-26T12:57:06Z
> An array *initializer* is allowed to have fewer elements. Actually that only seems to apply when the initializer is a string literal. char[4] s = [1]; // error char[4] s = "a"; // OK
Comment #5 by nick — 2024-01-26T14:09:06Z
Spec for above: > A string literal converts to a static array rvalue of the same or longer length https://dlang.org/spec/expression.html#string_literals
Comment #6 by robert.schadek — 2024-12-13T19:32:47Z
THIS ISSUE HAS BEEN MOVED TO GITHUB https://github.com/dlang/dmd/issues/20388 DO NOT COMMENT HERE ANYMORE, NOBODY WILL SEE IT, THIS ISSUE HAS BEEN MOVED TO GITHUB