3 ms·
Is it a guarantee that a 16 byte object would be 16 byte aligned?
by themafia 1y ago
Is it a guarantee that a 16 byte object would be 16 byte aligned?
- ComputerGuru 1y agoNo. It depends on the object.
- vidarh 1y agoNot in general, but it is a guarantee a runtime where all allocation are 16 byte cons cells can choose to make quite trivially.
- bluGill 1y agoIf you implement malloc you can do that. The os generally gives you 4k (or other number in that range) at a time and malloc subdivides it. language runtimes can call malloc whatever they want.
- secondcoming 1y agoIn C++ you can force that with alignas(), I would imagine other low level languages offer something similar. If you're using a custom allocator you'd have to enfore it yourself which should be fine since you have full control. https://en.cppreference.com/w/cpp/language/alignas.html https://en.cppreference.com/w/cpp/language/alignas.html
- sparkie 1y agoC23 also has `alignas` and `alignof` (`_Alignas`/`_Alignof` in C11 with the lowercase as macros in stdalign.h), and also provides `aligned_alloc` and `free_aligned_size` in stdlib.
- ksherlock 1y agoFor memory allocation, POSIX (posix_memalign) has been guaranteeing alignment since 2001. C11 added equivalent functionality (aligned_alloc). C++17 incorporated it (std::aligned_alloc) as well.
- fweimer 1y agoMore importantly, C++17 no longer ignores alignment in dynamic memory allocation: https://en.cppreference.com/w/cpp/memory/new/operator_new https://en.cppreference.com/w/cpp/memory/new/operator_new C++11 already had alignas, but it was not really integrated well.
- fweimer 1y agoDynamic languages usually come with their own memory manager. They can come up with their own alignment constraints. That being said, most contemporary (Linux) architectures require that malloc returns 16 byte alignned pointers. Some mallocs only promise this for allocations larger than 8 bytes, though (and I think the C standard was updated to permit that).