简体   繁体   English

内存对齐和分配与malloc

[英]memory alignment and allocation vs malloc

I am writing a library function in C that will return blocks of 32 bits. 我正在用C写一个库函数,它将返回32位的块。 I am using malloc() for this purpose. 我为此使用malloc()。 Will the following always guarantee that 32 bits of memory has been allocated in a contiguous fashion? 以下内容将始终保证以连续的方式分配32位内存吗?

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

How do I make sure that it is allocated over 4 byte boundary? 我如何确保它在4字节边界上分配?

Yes. 是。 You will get a contiguous block of 4 bytes of memory. 您将获得一个连续的4字节内存块。

Not 32 bytes. 不是32个字节。 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. 如果您指的是32位,则无法保证,但是在典型的台式机上, CHAR_BIT为8,然后,是的,您的4个字节等于32位。

是的,它将是连续的-但不必在4字节边界上分配它。

that's 4 bytes. 那是4个字节。 if you want 32 bytes to be contiguous then you should change the 4 to 32. 如果要连续32个字节,则应将4更改为32。

there is no guarantee that one malloc call allocates contiguously after the next and in fact implementations pad blocks. 不能保证一个malloc调用在下一个(实际上是实现)填充块之后连续分配。

sizeof(char) is always 1 . sizeof(char)始终为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. 强制转换malloc()的返回值也被许多人认为是不好的样式。

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: 如果您需要尽可能接近32位(最小开销)并且想要非常便携,则可能需要以下内容:

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. 标准malloc不保证返回的分配对齐。 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). 也没有一种可移植的方法来发现实际分配的大小,这使得访问超出请求大小的内存不安全且未定义(同样,某些实现可能提供扩展来解决这些问题)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM