Obsecure problem 1

rikki cattermole rikki at cattermole.co.nz
Sat Jul 30 21:48:35 UTC 2022


It is a pretty straight forward.

You tried to access memory out of bounds of the slice.

https://github.com/pascal111-fra/D/blob/main/dcollect.d#L34

That for loop is problematic in a number of ways.

You should not use int, or uint to index into memory, only size_t should 
be used. It is an alias to either uint or ulong based upon the size of a 
pointer.

```d
for(size_t i = ch.length - 1; i >= 0; i--)
```

Would be the corrected line.

However, it is still not correct, what happens when ch.length is zero? 
It'll wrap around and become a very large number. That is most likely 
what happened here.

To do this safely in D, use the foreach_reverse statement instead. There 
are very few reasons to use for loops in D.

https://dlang.org/spec/statement.html#foreach-range-statement

Adjusted:

```d
foreach_reverse(i; 0 .. ch.length)
```

However this is not efficient as you are reallocating constantly.

```d
char[] ch_rev;
ch_rev.length = ch.length;

size_t offset;
foreach_reverse(c; ch)
	ch_rev[offset++] = c;
```


More information about the Digitalmars-d-learn mailing list