[fpc-pascal] constructor "guarantee" and other behavioural stuff
pascaldragon at googlemail.com
Wed Jan 20 11:23:27 CET 2016
Am 20.01.2016 10:03 schrieb "Pierce Ng" <pierce at samadhiweb.com>:
> Hi all,
> I last used Pascal in school a long long time ago. Just discovered Free
> 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?
Note: "overload" is only necessary if you have multiple methods of the same
name with different parameters. What you probably meant is "override", but
even that is only necessary if a method in the parent was declared as
"virtual". For constructors this isn't normally necessary, except if you
want to use class variables to instantiate the class. E.g.
=== code begin ===
TNonceClass = class of TNonce;
c := TSomeSubNonce;
o := c.Create;
=== code end ===
In this example if the constructor in TNonce isn't declared as virtual (and
the on in TSomeSubNonce not as override) the TNonce.Create will be called,
otherwise TSomeSubNonce will be called.
> I'd imagine
> that, if randombytes() isn't called, the content of pn might be whatever
> happens to be in the memory that was allocated. By eyeballing, I won't be
> to tell, but cryptographically it'll be catastrophic if pn contains
> random-looking but possibly predictable data.
> On a related note, if I keep "filled" as an instance variable but leave
> line "filled := true" out from the constructor, what is filled's value
> after the constructor is done?
The memory area of a class instance is by default always initialized with
0s. So in this case "pn" will contain zeroes and "filled" will be "false".
Sidenote: Strings will be '', objects, interfaces and dynamic arrays will
> Finally, remembering my programming languages course from my CS undergrad
> in the following, are TNonce and TNonceBytes allocated on the stack or
> 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 ...
Classes are *always* allocated on the heap. If you want to control whether
something is allocated on the stack or the heap you need to use records or
the Turbo Pascal-style objects.
I can't answer your question regarding the security-sensitivity though.
-------------- next part --------------
An HTML attachment was scrubbed...
More information about the fpc-pascal