开发者

memory alignment and allocation vs malloc

开发者 https://www.devze.com 2023-03-14 22:56 出处:网络
I am writing a library function in C that will return blocks of 32 bits. I am using malloc() for this purpose. Will the following always guarantee that 32 bits of memory ha开发者_如何学编程s been allo

I am writing a library function in C that will return blocks of 32 bits. I am using malloc() for this purpose. Will the following always guarantee that 32 bits of memory ha开发者_如何学编程s been allocated in a contiguous fashion?

char *base_ptr = (char*)malloc(4*sizeof(char))?

How do I make sure that it is allocated over 4 byte boundary?


Yes. You will get a contiguous block of 4 bytes of memory.

Not 32 bytes. If you meant 32 bits then this is not guaranteed, but on a typical desktop machine CHAR_BIT is 8 and then, yes, your 4 bytes equate to 32 bits.


Yes it will be contiguous - BUT it won't necessary be allocated on a 4byte boundary.


that's 4 bytes. if you want 32 bytes to be contiguous then you should change the 4 to 32.

there is no guarantee that one malloc call allocates contiguously after the next and in fact implementations pad blocks.


sizeof(char) is always 1. There is no reason to write that in your code at all. Casting the return value of malloc() also considered bad style by many.

If you need to get as close to 32 bits as possible (minimum overhead) and you want to be extremely portable about it, you probably want something like:

char *base_ptr = malloc((32 + CHAR_BIT - 1) / CHAR_BIT);


Addressing the word "alignment" in the title.

Standard malloc makes no guarantees about the alignment of the allocation returned. Particular implementations may or may not do helpful things in the that realm, and may or may not have some kind of extension to allow you to control the alignment of the blocks returned. However, these things will not be portable.

As others have said each allocation is guaranteed to be continuous and at least as big as you requested; but there are no guarantees about the relative positioning of any pair of allocations. Nor is there a portable way to discover how large the actual allocation is, which makes it unsafe and undefined to access memory beyond the requested size (again, some implementations may provide extension that address these issues).

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号