I need to allocate 4 byte memory 开发者_Go百科and the allocated memory address should be the multiple of 4. eg:400, 404,408,40c
If I use any memory allocation function, I receive memory which are available and the addresses are not necessarily be in multiples of 4.
So can anyone suggest to achieve this design.
In the Microsoft C/C++ compiller you can use _aligned_malloc and in Linux posix_memalign .
MSVC:
ptr = _aligned_malloc(4, 4);
Signature:
void * _aligned_malloc(size_t size, size_t alignment);
Linux:
posix_memalign(&ptr, 4, 4); // returns 0 if successful
Signature (Note order is reversed compares to MSFT):
int posix_memalign(void **memptr, size_t alignment, size_t size);
Add 3 to your allocation amount. Allocate the memory. If the returned address isn't already a multiple of 4, round it up until it is. (The most you'd have to round up is 3, which is why you pad your allocation by that much in advance.)
When you free the memory, remember to free the original address, not the rounded-up value.
Guy Sirton gave the correct answer, but it is ambiguous and may lead to a potential bug.
The example there shows the value 4 for both size and alignment.
But the actual arguments of _aligned_malloc()
and posix_memalign()
are reversed:
_aligned_malloc( size_t size, size_t alignment )
posix_memalign(void **memptr, size_t alignment, size_t size)
A better example is non-symmetric, e.g.:
size_t alignment = 16; // Must be a power of 2
size_t size = 10; // Not necessarily a power if 2
#ifdef _MSC_VER
ptr = _aligned_malloc(size, alignment);
#else
posix_memalign(&ptr, alignment, size);
#endif
精彩评论