How many bytes does a string occupy in x64?

For training purposes, I am trying to understand how C # strings are stored inside memory.

According to this post , C # line size (x64 with .NET framework 4.0):

26 + 2 * length 

A line with one character will take (26 + 2 * 1) / 8 * 8 = 32 bytes . It really looks like what I measured.

What puzzle is for me is what is in these 26 bytes.

I ran the following code and verified memory:

 string abc = "abcdeg"; string aaa = "x"; string ccc = "zzzzz"; 

enter image description here

AFAIK these blocks are as follows:

  • Green: sync block (8 bytes)
  • Cyan: Enter information (8 bytes)
  • Yellow: length (4 bytes)
  • Pink: actual characters: 2 bytes per char + 2 bytes for the NULL terminator.

Look at the string "x". This is really 32 bytes (as calculated).

Anyway, it looks like the end of a line if filled with zeros. The string "x" may end after two bytes for the NULL terminator and still be memory aligned (thus, it is 24 bytes). Why do we need an additional 8 bytes?

I experimented with similar results with other (large) string sizes. It seems like there are always extra 8 bytes.

+5
source share

Source: https://habr.com/ru/post/1276138/


All Articles