如何管理内存路线和通用指针的算术在C移植的方式? [英] How to manage memory alignments and generic pointer arithmetics in a portable way in C?

查看:80
本文介绍了如何管理内存路线和通用指针的算术在C移植的方式?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我要实现的malloc / realloc的/自由的优化版本(我的特定应用定制)。目前的code在特定平台上运行,但我想它写在一个可移植的方式,如果可能的话(该平台可能会在未来改变),或者至少我想集中可能的平台差异在一个单一的点(可能是一个.h)中。我知道的一些问题:

I have to implement an optimized version of malloc/realloc/free (tailored for my particular application). At the moment the code runs on a particular platform, but I would like to write it in a portable way, if possible (the platform may change in the future), or at least I would like to concentrate the possible platform differences in a single point (probably a .h). I am aware of some of the problems:


  • 在内存对齐差异

  • 在最小的内存块的大小差异适用于普通的分配

  • 在指针大小差异

(我在这里忽略对存储器分配中的基本系统服务的差异,由于在某些嵌入式系统,他们可能不可用的。让我们假设我们大preallocated存储器块上工作以用作堆)。

(I'll ignore the differences in the basic system services for memory allocation here, since on some embedded systems they may be unavailable at all. Let's imagine that we work on a big preallocated memory block to be used as "heap").

问题(S):


  • 是否有标准的宏或函数C语言为这种目的?

  • 其他什么问题我可以在这个岗位上面对?

推荐答案

对齐功能仅在新的C标准,C11处理。它有关键字 _Alignof _Alignas 和功能 aligned_alloc 。论文的特点是不是很难与最现代的编译器(在其他的答案表示)效仿,那么我建议你写你自己,你会使用这取决于 __ STDC_VERSION __

Alignment features are only handled in the new C standard, C11. It has keywords _Alignof, _Alignas and a function aligned_alloc. Theses features are not very difficult to emulate with most modern compilers (as indicated in other answers), so I'd suggest you write yourself small macros or wrappers that you'd use depending on __STDC_VERSION__.

这篇关于如何管理内存路线和通用指针的算术在C移植的方式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆