Dynamic array as a typed constant can easily be modifed
Summary
With writable constants off typed constant dynamic array can easily be modified.
System Information
- Operating system: Linux (Arch Linux)
- Processor architecture: x86-64
- Compiler version: 3.3.1-12060-g3db1415a
- Device: Computer
Steps to reproduce
Compile and run the following program:
program testarr;
{$mode objfpc}
{$WriteableConst off}
const
i_arr: array of integer = (1, 2, 3);
var
i: integer;
begin
for i := 0 to high(i_arr) do begin
inc(i_arr[i]);
writeln(i_arr[i]);
end;
end.
Example Project
See "Steps to reproduce"
What is the current bug behavior?
$ fpc testarr.pas && ./testarr
Free Pascal Compiler version 3.3.1 [2022/11/05] for x86_64
Copyright (c) 1993-2022 by Florian Klaempfl and others
Target OS: Linux for x86-64
Compiling testarr.pas
Linking testarr
13 lines compiled, 0.1 sec, 143856 bytes code, 55040 bytes data
2
3
4
What is the expected (correct) behavior?
Because this regarding a complete typed constant I expected the compiler to say I could not do the following: inc(i_arr[i]);
To be explicit, this is what I expected:
Free Pascal Compiler version 3.3.1 [2022/11/05] for x86_64
Copyright (c) 1993-2022 by Florian Klaempfl and others
Target OS: Linux for x86-64
Compiling testarr.pas
testarr.pas(10,9) Error: Can't assign values to const variable
testarr.pas(14) Fatal: There were 1 errors compiling module, stopping
Fatal: Compilation aborted
Error: /home/dev/fpc_usr/lib/fpc/3.3.1/ppcx64 returned an error exitcode
I expect this because when I try to modify a complete typed constant record the compiler says it can't assign values to a const variable.
Example:
program testrec;
{$mode objfpc}
{$WriteableConst off}
type
SomeRec = record
a: integer;
end;
const
rec: SomeRec = (a: 5);
begin
inc(rec.a);
writeln(rec.a);
end.
When trying to compile that I get:
Free Pascal Compiler version 3.3.1 [2022/11/05] for x86_64
Copyright (c) 1993-2022 by Florian Klaempfl and others
Target OS: Linux for x86-64
Compiling testrec.pas
testrec.pas(14,7) Error: Can't assign values to const variable
testrec.pas(17) Fatal: There were 1 errors compiling module, stopping
Fatal: Compilation aborted
Error: /home/dev/fpc_usr/lib/fpc/3.3.1/ppcx64 returned an error exitcode
Which I consider to be correct behavior, because of "writable constants off" and this an attempt at direct modification of a typed constant.
Relevant logs and/or screenshots
See "What is the current bug behavior?"