[fpc-pascal] Does SetLength clear its elements to zeros?

Mark Morgan Lloyd markMLl.fpc-pascal at telemetry.co.uk
Fri Dec 11 11:56:11 CET 2015

Jonas Maebe wrote:
> Dennis wrote on Fri, 11 Dec 2015:
>> I just tested, SetLength a string  does not zero its elements (the 
>> chars).
>> However, SetLength a dynamic array seems to zero its elements.
> Dynamic arrays are indeed zeroed when changing the length, while strings 
> are not. For dynamic arrays, it is necessary anyway in case it has 
> reference counted elements. Maybe for consistency, it's always done.
> Additionally, changing the length of the string without afterwards 
> overwriting the data between the previous and new last character seems 
> something that would happen very seldom (why did you increase the length 
> if you didn't need to write all characters -- any operation with the 
> string, such as writing or concatenating it, will use those characters 
> anyway because the length indicates they're part of the string).
> The above are mostly guesses though.

Setlength(zero) would be significant if somebody were trying to wipe a 
field that's just been used for password verification.

I'd suggest that this is related to the general issue of whether a 
string that is reallocated due to a substantial length increase is 
wiped, which I think was tentatively fixed by providing an alternative 
memory manager (discussed back when "Heartbleed" was an issue).

I notice that you can now get memory analysis tools that report when a 
block is either more or less random than would be expected, suggesting 
that zeroing sensitive data might not in fact be the best approach.

Mark Morgan Lloyd
markMLl .AT. telemetry.co .DOT. uk

[Opinions above are the author's, not those of his employers or colleagues]

More information about the fpc-pascal mailing list