Passing dynamic arrays

Jonathan M Davis jmdavisProg at gmx.com
Mon Nov 8 10:54:38 PST 2010


On Monday, November 08, 2010 10:35:38 Daniel Gibson wrote:
> bearophile schrieb:
> > Jens Mueller:
> >> I find this behavior rather strange.
> > 
> > I don't know if it's strange, but surely it is a little bug-prone corner
> > of D. I have had two or three bugs in my code because of that.
> 
> If you pass a dynamic array to a function and chance it's size within the
> function, you have undefined behaviour - you never know if it will affect
> the original array (from the calling function) or not.

Implementation-defined behavior would be more accurate. Undefined would mean that 
it's something dangerous which is not defined by the language, and you shouldn't 
be doing. It's perfectly defined by the language in this case. It's just that how 
much extra memory is allocated for a dynamic array is implementation-defined, so 
in cases where a reallocation would be necessary because the array ran out of 
memory, it's implementation-dependent as to whether or not a reallocation will 
be necessary or not. In every other case, it's completely language-defined and 
deterministic. The algorithm for additional capacity is the only part that 
isn't.

> So IMHO a compiler warning would  be appropriate in that case.
> 
> (It would be even better to have more consistent array handling throughout
> the different kinds of arrays, as I wrote in another branch of this
> thread, but if that is no option, for example because it contradicts TDPL,
> a compiler warning is a good compromise)

Honestly, if you want an array that you're passing in to be altered by the 
function that you're passing it to, it really should be passed by ref anyway. 
And if you want to guarantee that it isn't going to be altered, make it const, 
dup it, or have its individual elements be const or immutable. Problem solved. I 
really don't see this as an issue. I can understand why there might be some 
confusion - particularly since the online docs aren't very clear on the matter, 
but it really isn't complicated, and I'd hate to have to dup an array just to be 
able to append to it, which is what the warning that you're suggesting would 
require. A compiler warning is as good as an error really, since you're going to 
have to fix it anyway, so I'd definitely be against making this either an error or 
a warning. I see no problem with being allowed to resize arrays that are passed 
to functions.

- Jonathan M Davis


More information about the Digitalmars-d mailing list