Page 1 of 1

How many extra bytes are in the string?

Posted: Thu May 22, 2025 7:40 pm
by AZJIO
I have heard that when creating a string, a little more bytes are allocated than necessary, so when adding a pair of CRLF characters to a string, there is no memory overallocation (ReAllocateMemory) and it works quickly. I'm wondering how many bytes are allocated more than required. How many characters can I add to a string without causing memory overload.

Re: How many extra bytes are in the string?

Posted: Thu May 22, 2025 8:20 pm
by skywalk
Ouch, that is not guaranteed behavior. :evil:
You must assume your string byte length is accurate and not use "behind the scenes" padding.

Re: How many extra bytes are in the string?

Posted: Thu May 22, 2025 9:04 pm
by AZJIO
skywalk wrote: Thu May 22, 2025 8:20 pm and not use "behind the scenes" padding.
This will be the standard method

Code: Select all

strind + #CRLF$ + #TAB$
But I want to make sure that +#TAB$ doesn't cause memory over-allocation.

I want to know in which case I can use the normal method and in which case I have to use the CopyMemoryString() function.

Re: How many extra bytes are in the string?

Posted: Thu May 22, 2025 9:05 pm
by mk-soft
It is requested as much memory as one needs and goes coherently.

You can also forcibly release the string memory ;)

Start without debugger as console and watch memory

Code: Select all

Define i.i, s.s

mb = 1024*1024*16

If OpenConsole()
  i + 1
  PrintN("" + i + ": no string")
  Input()
  i + 1
  s = Space(mb)
  PrintN("" + i + ": 16mb unicode string")
  Input()
  i + 1
  s + Space(mb)
  PrintN("" + i + ": plus 16mb unicode string")
  Input()
  i + 1
  PrintN("" + i + ": release string")
  s = #Null$
  Input()
  
EndIf

Re: How many extra bytes are in the string?

Posted: Sat May 24, 2025 9:21 pm
by SMaag
I struggled with this at my early Assembler tests with Strings. At the beginning I did not understand what are the values after the end of the String.

The allocation is 4 Byte aligned at x86 and 8 Byte aligend at x64. So number of charcters * SizeOf(Charcter) + CHR(0) + FillBytesForMemoryAling
So you can write without problems until the end of the aligned size. At x64 and Charsiez=2 this are maximal 3 characters more than you String.

Re: How many extra bytes are in the string?

Posted: Sat May 24, 2025 11:15 pm
by mk-soft
PureBasic decides internally how much memory is reserved behind the string ...

Code: Select all

Define a$

For i = 1 To 100
 a$ + "x"
 Debug "pString = " + @a$
Next