GCC:__attribute __((malloc的)) [英] GCC: __attribute__((malloc))

查看:1634
本文介绍了GCC:__attribute __((malloc的))的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

文档引用(重点煤矿):

的malloc的属性是用来告诉编译器功能可能
  被视为如有非NULL指针返回不了任何的别名
  其他指针当函数返回和内存具有有效
  未定义的内容
。这往往提高了优化。标准
  与此属性的功能包括的malloc 释放calloc 的realloc
  函数没有这个属性为指向的内存不
  有不确定的内容。

The malloc attribute is used to tell the compiler that a function may be treated as if any non-NULL pointer it returns cannot alias any other pointer valid when the function returns and that the memory has undefined content. This often improves optimization. Standard functions with this property include malloc and calloc. realloc-like functions do not have this property as the memory pointed to does not have undefined content.

我有以下的code:

struct buffer {
    size_t alloc;  // Allocated memory in bytes
    size_t size;   // Actual data size in bytes
    char data[];   // Flexible array member
};


#define ARRAY_SIZE <initial_value>

buffer *buffer_new(void) __attribute__((malloc))
{
    struct buffer *ret;

    ret = malloc(sizeof(struct buffer) + ARRAY_SIZE);
    if (!ret)
        fatal(E_OUT_OF_MEMORY);

    ret->alloc = ARRAY_SIZE;
    ret->size = 0;

    return ret;
}

现在我在这里有点纳闷:虽然我没有初始化数据成员,我仍然将页头尺寸字段,以它们各自的值。我还可以考虑这个分配段是不确定的内容,使用的的malloc 的属性?

Now I'm a bit puzzled here: though I didn't initialize the data member, I still set the alloc and size fields to their respective values. Can I still consider this allocated segment to be of "undefined content" and use the malloc attribute?

推荐答案

这是安全与标记您的buffer_new功能的属性((malloc的)),因为它返回块不包含任何指针。

It is safe to mark your buffer_new function with attribute((malloc)), because the block it returns contains no pointers.

最新的GCC文档澄清的意思的属性((malloc的)):由如此标记不能包含任何的指向其他对象函数的返回块的。其目的是帮助编译器估计其中三分球有可能会点进去相同的对象:该属性告诉GCC则不必担心你的目标函数返回可能包含指向别的东西它跟踪

The latest GCC documentation clarifies the meaning of attribute((malloc)): the block returned by a function so marked must not contain any pointers to other objects. The intention is to help the compiler estimate which pointers might possibly point into the same object: the attribute tells GCC it needn't worry that the object your function returns might include pointers to something else it's tracking.

这篇关于GCC:__attribute __((malloc的))的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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