Obsecure problem 1

pascal111 judas.the.messiah.111 at gmail.com
Sat Jul 30 22:17:10 UTC 2022


On Saturday, 30 July 2022 at 21:48:35 UTC, rikki cattermole wrote:
> 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;
> ```

Your suggestion works. It seems a problem with that "for" loop, 
but I don't know exactly from where it got a 0 or subtracted of 0.

I changed data types of some parameters and for loops, and 
changed that for loop as you suggested:

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

The program works fine now:

https://i.postimg.cc/3wkgXmVs/Screenshot-from-2022-07-31-00-04-23.png


More information about the Digitalmars-d-learn mailing list