[fpc-pascal] constructor "guarantee" and other behavioural stuff
Michael Van Canneyt
michael at freepascal.org
Wed Jan 20 11:22:20 CET 2016
On Tue, 19 Jan 2016, Pierce Ng wrote:
> Hi all,
> I last used Pascal in school a long long time ago. Just discovered Free Pascal.
> I have the following:
> TNonceBytes = array[1..8] of byte;
> TNonce = class
> pn: TNonceBytes;
> filled: boolean;
> constructor create; overload;
> constructor TNonce.create;
> randombytes(pn, 8);
> filled := true;
> Is "filled" necessary, or does the compiler guarantee that my overloaded
> constructor is called to fill "pn" with "real crypto" random bytes?
> I'd imagine
> that, if randombytes() isn't called, the content of pn might be whatever that
> happens to be in the memory that was allocated. By eyeballing, I won't be able
> to tell, but cryptographically it'll be catastrophic if pn contains
> random-looking but possibly predictable data.
It will be instantiated with 0 when the constructor is called.
> On a related note, if I keep "filled" as an instance variable but leave the
> line "filled := true" out from the constructor, what is filled's value
> after the constructor is done?
The whole memory area used by an instance of a class is zeroed out.
> Finally, remembering my programming languages course from my CS undergrad days,
> in the following, are TNonce and TNonceBytes allocated on the stack or from the
> heap, and should I care, given that, in this case, I am writing a
> security-sensitive program?
> procedure encrypt(ptext: TByteArray, var ctext: TByteArray);
> n: TNonce;
> n := TNonce.create;
> ... whatever ...
a TNonce instance is allocated on the heap. All classes are allocated on the heap.
TNonceBytes as a fixed-length array is part of the memory allocated for TNonce.
There are also the older style "objects", they are allocated on the stack.
More information about the fpc-pascal