Memory alignment question

    This site uses cookies. By continuing to browse this site, you are agreeing to our Cookie Policy.

    • Memory alignment question

      (EDIT) it was std::string b; NOT int b;
      Sorry about that.

      Hi all! I am a new software engineer (working for 2 years now) and I am doing my start at video game programming!

      I am curently starting to code my game and I am doing a memory manager.

      My question is: Mike in his book says: "Any N-byte data type is memory aligned if the starting address is evenly divisible by N".

      My problem is:

      I create a small program:

      int main()
      char a;
      std::string b;

      std::cout << sizeof(b) << std::endl;

      std::cout << &b << std::endl;

      The result I get is:

      So, the problem is that (hex)003bf864 = (dec)3930212 % 32 != 0 !

      So, does that mean that my string is not aligned?


      The post was edited 1 time, last by Torous ().

    • Right. After a lot of research and testing, it looks like there is a mistake in the book. Actually, if A is the returned address, then A%L = 0, where L is the alignment requirement of the type, NOT the size of the type. In my example,

      (hex)003bf864 = (dec)3930212 % 4 = 0.

      4, because the alignment requirement of std::strings is 4.

      Can anyone confirm/debunk or add something to that please? Any comment is really appreciated.
    • Hi,

      the alignment you've quoted is called natural alignment. As you've discovered not everything is naturally aligned (actually a lot of CPUs can't even handle arbitrary memory-access to multi-byte words, but x86 is not one of them, so you could put your std::string on any address-boundary you wish).

      Using a 4 byte-alignment to read a 4-byte word is efficient for a cpu because it can read all 4 bytes very easily by using the following addresses (addr is the base address - the address of the first byte):
      (addr & ~3) + ((addr + 1) & 3)
      (addr & ~3) + ((addr + 2) & 3)
      (addr & ~3) + ((addr + 3) & 3)