Thread overview | ||||||
---|---|---|---|---|---|---|
|
August 07, 2010 Slicing to convert pointers to bound arrays | ||||
---|---|---|---|---|
| ||||
I understand this is an unsafe operation, I just have a quick question. Here, b points outside a's memory, so I get garbage. { int[] a = [3,3,3]; auto p = a.ptr; auto b = p[0..3]; assert(b == [3,3,3]); b = p[0..4]; // b == [3,3,3,?] } When I do the same with a static array, I get 0. But this is just actually garbage, right? It might contain other data, and not always 0? { int[3] a = [3,3,3]; auto p = a.ptr; auto b = p[0..3]; assert(b == [3,3,3]); b = p[0..4]; assert(b == [3,3,3,0]); } |
August 07, 2010 Re: Slicing to convert pointers to bound arrays | ||||
---|---|---|---|---|
| ||||
Posted in reply to simendsjo | simendsjo:
> When I do the same with a static array, I get 0. But this is just actually garbage, right? It might contain other data, and not always 0?
Generally it contains "garbage".
In string literals there is one more item that's empty (zero). I don't know if normal fixed-sized arrays too have the extra leading zero item (maybe yes), but relying on it is surely bad programming practice.
Bye,
bearophile
|
August 07, 2010 Re: Slicing to convert pointers to bound arrays | ||||
---|---|---|---|---|
| ||||
Posted in reply to simendsjo | On 07/08/2010 13:45, simendsjo wrote: > > When I do the same with a static array, I get 0. But this is just > actually garbage, right? It might contain other data, and not always 0? Yes. It's entirely undefined what will happen, you might find that the extra bit of memory you try and access is a non readable page which will give you a seg fault or it could be any random chunk of data depending on how the executable gets linked. -- My enormous talent is exceeded only by my outrageous laziness. http://www.ssTk.co.uk |
August 08, 2010 Re: Slicing to convert pointers to bound arrays | ||||
---|---|---|---|---|
| ||||
Posted in reply to bearophile | On 07.08.2010 16:48, bearophile wrote:
> simendsjo:
>> When I do the same with a static array, I get 0. But this is just
>> actually garbage, right? It might contain other data, and not always 0?
>
> Generally it contains "garbage".
> In string literals there is one more item that's empty (zero). I don't know if normal fixed-sized arrays too have the extra leading zero item (maybe yes), but relying on it is surely bad programming practice.
>
> Bye,
> bearophile
Ok, thanks. I expected this, but It's good to get it verified.
|
Copyright © 1999-2021 by the D Language Foundation