digitalmars.D.learn - Slicing to convert pointers to bound arrays
- simendsjo (19/19) Aug 07 2010 I understand this is an unsafe operation, I just have a quick question.
- bearophile (5/7) Aug 07 2010 Generally it contains "garbage".
- simendsjo (2/9) Aug 08 2010 Ok, thanks. I expected this, but It's good to get it verified.
- div0 (8/10) Aug 07 2010 Yes. It's entirely undefined what will happen, you might find that the
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]); }
Aug 07 2010
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
Aug 07 2010
On 07.08.2010 16:48, bearophile wrote:simendsjo:Ok, thanks. I expected this, but It's good to get it verified.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
Aug 08 2010
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
Aug 07 2010