[fpc-devel] an idea about "const param: string"

Martin lazarus at mfriebe.de
Sat May 28 22:08:41 CEST 2011


I know there are lots of ideas, and many ideas without the person from 
whom it originates being able or willing to work on it.
This is one of them. So if it will simply vanish, never mind. Anyway 
maybe I am lucky, and with this idea I plant a seed, and someday....

I recently run across the following situation (again)

procedure Foo(const s: string;)
begin
   // do something
   CallBar();
   // do more
end;
var GlobalText: String
Foo(GlobalText);

and then in CallBar, "GlobalText" is modified. Which is not allowed.
http://lists.freepascal.org/lists/fpc-devel/2010-July/020966.html
http://lists.freepascal.org/lists/fpc-devel/2010-July/020974.html

The problem of course is that such code is incredible hard to find.

I was thinking it would be cool to have something like range-checks, but for those strings.

Ideally, the string would be flagged, and other code trying to access it would check this. But that would mean that all units, packages everything would need awareness, and had to be compiled with support for the flag.... Not really practical.

However at least some test would probably work.
If compiled with -Cc (Check Constant string param) or whatever compiler option it would be, then the code in Foo could have checks.

If foo would copy the value of s (only the address: @s[0], not the string) and increase the ref-count of s (it still is a pointer to the original s), then Foo could check on exit.
If anyone modified s, then copy-on-write would have kicked in. either the address in s, or the ref count would have changed.

That would allow to give at least a warning that something wrong was done.

Martin



More information about the fpc-devel mailing list