Don't use arrays as stacks

Jonathan M Davis jmdavisProg at gmx.com
Sun Sep 25 04:18:13 PDT 2011


On Sunday, September 25, 2011 07:05:34 Nick Sabalausky wrote:
> "Jonathan M Davis" <jmdavisProg at gmx.com> wrote in message
> news:mailman.160.1316939358.26225.digitalmars-d at puremagic.com...
> 
> > On Sunday, September 25, 2011 03:18:29 Andrew Wiley wrote:
> >> Isn't this exactly what assumeSafeAppend is for?
> 
> Hmm, I didn't know about that. (Actually, I remember hearing it mentioned
> before, but then totally forgot about it.)
> 
> > and if you're using assumeSafeAppend, then you
> > need to guarantee that nowhere else has a reference to that array
> > (otherwise
> > it's _not_ safe to assume that it's safe to append)
> 
> Would the consequences of failing to do that be any worse (or any different
> at all?) than what I mentioned about:
> 
> "One caveat about this method: If you save a slice of the stack, pop
> elements off the stack, and then push new values back on, the old slice you
> took will likely reflect the new values, not the original ones."
> 
> ...?

I'm not sure. If you have 2 slices which point to the same memory, and one is 
longer than the other, and then you call assumeSafeAppend on the smaller one, 
then if you append to the smaller one, it will increase its size into the 
smaller one, which may or may not cause issues depending on what you're doing. 
The real potential issue though is what happens if you use the longer slice 
and append to it. I really don't know what happens at that point. It'll 
probably just adjust the information on that block such that the pointer (or 
length - I'm not sure which it is) that it keeps to the end of the longest 
slice may be adjusted accordingly, or it could cause issues, because the end 
of that slice is already beyond what the block thinks is the end of the 
longest slice.

So, the problem is more or less the same as the situation that you gave, but 
I'm not sure that it's identical. Regardless, it's just safer to wrap the 
array in a stack struct and not give access to the array. Normally all you 
care about with a stack is pushing and popping elements on and off and possibly 
peeking at the top element - none of which require having access to the array 
- so wrapping the array and not giving external access to it should work just 
fine.

- Jonathan M Davis


More information about the Digitalmars-d mailing list