www.digitalmars.com         C & C++   DMDScript  

digitalmars.D.learn - Slicing to convert pointers to bound arrays

reply simendsjo <simen.endsjo pandavre.com> writes:
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
next sibling parent reply bearophile <bearophileHUGS lycos.com> writes:
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
parent simendsjo <simen.endsjo pandavre.com> writes:
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.
Aug 08 2010
prev sibling parent div0 <div0 sourceforge.net> writes:
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