Recent

Author Topic: Corrupted strings  (Read 510 times)

LemonParty

  • Sr. Member
  • ****
  • Posts: 393
Corrupted strings
« on: December 05, 2025, 03:02:10 pm »
Hello.

Let's say we have this code:
Code: Pascal  [Select][+][-]
  1. var
  2.   S: String = '12345';
  3. begin
  4.   S[3]:= #0;
  5. end.
  6.  
Is string after this manipulation become corrupted? How should be processed zeroes in the middle of the string?
Lazarus v. 4.99. FPC v. 3.3.1. Windows 11

marcov

  • Administrator
  • Hero Member
  • *
  • Posts: 12596
  • FPC developer.
Re: Corrupted strings
« Reply #1 on: December 05, 2025, 03:14:27 pm »
A Pascal string can contain any character as the length is stored separately, so that would simply be a pascal string with a null character in third position.

However since many GUI and console libraries are C based, they often can't deal with nulls, as they see it as the end of a string.

So in summary, that construct is fine, but displaying it can be troublesome.

jamie

  • Hero Member
  • *****
  • Posts: 7493
Re: Corrupted strings
« Reply #2 on: December 05, 2025, 03:28:16 pm »
Code: Pascal  [Select][+][-]
  1. SelLength(S, Pos(#0,S));
  2.  

Something like that.
The only true wisdom is knowing you know nothing

LemonParty

  • Sr. Member
  • ****
  • Posts: 393
Re: Corrupted strings
« Reply #3 on: December 05, 2025, 05:13:18 pm »
Thank you.
Lazarus v. 4.99. FPC v. 3.3.1. Windows 11

Aruna

  • Hero Member
  • *****
  • Posts: 776
Re: Corrupted strings
« Reply #4 on: December 06, 2025, 08:25:44 pm »
Hello.

Let's say we have this code:
Code: Pascal  [Select][+][-]
  1. var
  2.   S: String = '12345';
  3. begin
  4.   S[3]:= #0;
  5. end.
  6.  
Is string after this manipulation become corrupted? How should be processed zeroes in the middle of the string?

You are replacing '3' (the third character) with #0. So internally, the string bytes become:

S[1] = '1'
S[2] = '2'
S[3] = #0
S[4] = '4'
S[5] = '5'

The length of S is still 5. Nothing is automatically truncated. The string is not corrupted, but you need to be careful when interfacing with routines that expect null-terminated strings. I have attached a zip for you to play around with. Have fun!

 

TinyPortal © 2005-2018