any news on const/invariant?

Regan Heath regan at netmail.co.nz
Tue Nov 27 02:14:32 PST 2007


Frank Benoit wrote:
> Regan Heath schrieb:
>> Walter Bright wrote:
>>> Regan Heath wrote:
>>>> void foo(char[] pbuffer)
>>>> {
>>>>   //assume this causes reallocation
>>>>   //assume there is no more space in place
>>>>   pbuffer ~= "a";
>>>> }
>>>>
>>>> void main()
>>>> {
>>>>   char[] buffer = "test".dup;
>>>>   foo(buffer);
>>>>   buffer[0] = 'a' //crash
>>>> }
>>>>
>>>> Right?
>>> No. foo() modifies its copy of pbuffer, which is not the same as buffer.
>> Yes, but the underlying memory is reallocated so buffer no longer points
>> to valid memory, right?
>>
>> Regan
> 
> You missed a semicolon, so it does not compile :)
> Realloc does not destroy the original buffer. So your foo just make a
> modified copy, that is not visible for the caller. buffer will stay
> unchanged.

'realloc' (the ANSI C version) free's the original buffer.

Are you saying that when D extends an array buffer, and there is no 
space to extend in place, it always creates a 2nd copy of the data and 
leaves the original copy untouched?

Because, I was under the impression that completely new copies were only 
made on concatenation in this form:

char[] a = b ~ c;

I'll try and code up a test case that exhibits the behaviour I'm worried 
about, but it's hard when I don't really have control of the array 
memory allocation/re-allocation itself.. or do I..

I wonder if this would fix the problem:

void foo(const(char[]) pbuffer) { ... }

would reallocation of the data pointer in this array be prevented?

If so, I reckon we should be passing either:

   const(char[]) array
   ref char[] array;

and never:

   char[] array

Regan



More information about the Digitalmars-d mailing list