Safety check for "const s: string" (similar to Range or Overflow checks)
Original Reporter info from Mantis: Martin @martin_frb
-
Reporter name: Martin Friebe
Original Reporter info from Mantis: Martin @martin_frb
- Reporter name: Martin Friebe
Description:
The compiler offers the developer tools to detect certain bugs at runtime. e.g range check will check array indexes, and report an error if violated at run time.
I'd like to suggest the addition of such a check for "const string" parameters
In code like
procedure Foo(const s: string);
"s" can not be changed, but Foo can be called with a global variable. If this global variable is changed while in Foo (or by any procedure called from within Foo) the behavior is unpredictable (as s still points to the old, potentially freed string), and random crashes can occur. Such errors may be very hard to trace.
I believe it is possible to check for such violations at runtime, in a way that all code required for the check can be done in "Foo".
If compiled with a "check const param" switch (e.g -Cc or -Cp whatever is not taken) then:
- On entering "Foo" the ref count of "s" will be increased.
- Yes this may in rare conditions change behavior of the application, but the developer should know if applying the switch
- This will lead to the implicit exception frame being created, that might otherwise have been optimized away.
The ref count of s at this point will be 2 or greater. (except the empty string)
- On exit of Foo, the ref-count of s is verified.
- The ref-count may have increased, as additional references to the global var may have been created.
If it was greater than 2, it may even have been decreased.
- The ref count must however be at least 2.
If (all of) the global var, was (were) modified, it would have triggered "copy on write" and the ref-count of "s" would then be down to 1.
In addition, inside of Foo, any variable that is set to be a copy of "s" ( SomeVar := s ) must also check, for the ref count of "s" being 2 or greater at this time.
Otherwise "S" is already invalid, and this statement would increase the ref count of the invalid "s", and would cause "s" to look ok, while it is not.
Mantis conversion info:
- Mantis ID: 19605
- OS: win
- OS Build: vista
- Platform: w32
- Version: 2.5.1
- Monitored by: » Ask (Alexander S. Klenin), » @MageSlayer (Denis Golovan)