Potential buffer overflow when using shortstring var/out parameters
A discussion regarding shortstrings revealed a shortcoming of the current implementation, where shortstring parameters are assumed to be 255 bytes in length, regardless of the actual declaration of the parameter being passed in. This can lead to buffer overflows, as illustrated below:
- Operating system: Embedded, Linux Mint
- Processor architecture: AVR, x86-64
- Compiler version: main 569f83e3
- Device: microcontroller, PC
Steps to reproduce
Pass a shortstring with size smaller than 255 bytes to subroutines that writes more data to the parameter that the original variable's size. See example project.
program project1; var s1: string = 'wxyz'; s2: string = '??'; procedure setStr(out s: shortstring); begin s := '1234'#09'SURPRISE!'; end; begin setStr(s1); writeln(s1); writeln(s2); end.
What is the current bug behavior?
Actual output (Linux-64 and AVR):
1234 SURPRISE! SURPRISE!
What is the expected (correct) behavior?
Relevant logs and/or screenshots
Sven suggested passing the shortstring size as an extra parameter to var (and I assume out) parameters. This comment was for a specific situation (eliminating a temporary variable during string concatenation), but sounds like a general solution to the problem.