Beginning Rust by Carlo Milanesi

Beginning Rust by Carlo Milanesi

Author:Carlo Milanesi
Language: eng
Format: epub
Publisher: Apress, Berkeley, CA


This, in a 64-bit system, may print:

0x1 0 0

0x7fbf95e20020 4 1

0x7fbf95e20020 4 2

0x7fbf95e20020 4 3

0x7fbf95e20020 4 4

0x7fbf95e20020 8 5

0x7fbf95e20020 8 6

0x7fbf95e20020 8 7

0x7fbf95e20020 8 8

0x7fbf95e2a000 16 9

0x7fbf95e2a000 16 10: aaaaaaaaaa

The as_ptr function (to be read “as pointer”) returns the address of the heap-allocated buffer containing the characters of the string .

Notice that when the string is empty, such address is simply 1, which is an invalid memory address, because no buffer is allocated for a string just created as empty.

When one ASCII character is added, a 4-byte buffer is allocated at an address represented by the hexadecimal number 7fbf95e20020.

Adding three other characters, no reallocations are required because the buffer is large enough.

When the fifth character is added, a reallocation is required, but, as the memory immediately following the buffer is still free, the buffer may be simply extended to 8 bytes, so avoiding the overhead of allocating a new buffer, copying the four used bytes, and deallocating the previous buffer.

Again, adding 3 other characters, no reallocations are required, but when the ninth character is added, not only the buffer is to be extended to 16 bytes, but it has to be relocated, as, presumably, not every one of the 8 next bytes is free.

At the end, the string uses 10 bytes.



Download



Copyright Disclaimer:
This site does not store any files on its server. We only index and link to content provided by other sites. Please contact the content providers to delete copyright contents if any and email us, we'll remove relevant links or contents immediately.