Bug 22673 – .array of a range with length preallocates without checking if the length was lying or not.
Status
RESOLVED
Resolution
FIXED
Severity
normal
Priority
P1
Component
phobos
Product
D
Version
D2
Platform
x86_64
OS
Linux
Creation time
2022-01-13T22:34:08Z
Last change time
2022-01-26T11:25:09Z
Keywords
pull
Assigned to
No Owner
Creator
mhh
Comments
Comment #0 by maxhaton — 2022-01-13T22:34:08Z
```
struct Range
{
enum size_t length = 100;
enum size_t evilRealLength = 50;
size_t idx;
Type front()
{
return Type(0);
}
bool empty()
{
return idx == evilRealLength;
}
void popFront()
{
++idx;
}
}
```
This will allocate 100 `Type`s but only 50 will be touched, what happens if those later ones get destructed?
Comment #1 by destructionator — 2022-01-13T22:40:38Z
The others will be in the .init state, which should mean the destructor is a no-op on them.
Comment #2 by maxhaton — 2022-01-14T00:51:07Z
The array allocated is uninitialized.
```
auto result = (() @trusted => uninitializedArray!(Unqual!E[])(length))();
```
Comment #3 by destructionator — 2022-01-14T00:59:34Z
ah i see yeah that's good good.
the fix would prolly be to just bit some init over and slice it off then at the end
Comment #4 by maxhaton — 2022-01-14T01:08:15Z
(In reply to Adam D. Ruppe from comment #3)
> ah i see yeah that's good good.
>
> the fix would prolly be to just bit some init over and slice it off then at
> the end
I kind of think this should actually error or throw, because I think it's a bit iffy letting these kinds of things fester. There's a wider problem though, if something throws when filling the array up then it will be finalized with (what must be assumed to be, even if it is zero) junk. For that the fix I have is to just write T.init into the memory before passing the exception (this might be a case to catch Throwable) up.
Slightly painful to test, I can't quite get the GC to collect before I try and check all the destructions were valid. I might have to put an assert in the destructor (bitch to debug if it ever breaks)
Comment #5 by dlang-bot — 2022-01-14T22:35:53Z
@maxhaton created dlang/phobos pull request #8359 "Fixes issues 22185, 22673" fixing this issue:
- Fixes issues 22185, 22673
https://github.com/dlang/phobos/pull/8359
Comment #6 by dlang-bot — 2022-01-26T11:25:09Z
dlang/phobos pull request #8359 "Fixes issues 22185, 22673" was merged into master:
- 4eff7e2a312f70cd5a576bcfdd63d8b0022c68b4 by Max Haughton:
Fixes issues 22185, 22673
https://github.com/dlang/phobos/pull/8359