Search code examples
cglib

GLib macro g_slice_new questions


This question related to GLib for c programming. The original code here: https://github.com/GNOME/glib/blob/master/glib/gslice.h

In glist.h, I saw the macro _g_list_alloc0 and I want to know how it implements.So I back track.

#define _g_list_alloc0() g_slice_new0 (GList)

Next, back tracking to the macro g_slice_new0

#define  g_slice_new0(type) ((type*) g_slice_alloc0 (sizeof (type)))

Ok, back tracking to

gpointer g_slice_alloc0 (gsize block_size) G_GNUC_MALLOC G_GNUC_ALLOC_SIZE(1);

For the G_GNUC_MALLOC, I found it actually is:

#define G_GNUC_MALLOC __attribute__((__malloc__))
#define G_GNUC_ALLOC_SIZE(x) __attribute__((__alloc_size__(x)))

I am confused about the last two macros G_GNUC_MALLOC and G_GNUC_ALLOC_SIZE.

Can I replace the G_GNUC_ALLOC_SIZE(1) and G_GNUC_MALLOC with the:

__attribute__((__alloc_size__(1)))
__attribute__((__malloc__))

So, replace the macro

gpointer g_slice_alloc0 (gsize block_size) G_GNUC_MALLOC G_GNUC_ALLOC_SIZE(1);

The macro actually defines like that:

gpointer g_slice_allo0 (gsize block_size) 
__attribute__((__malloc__))   __attribute__((__alloc_size__(1)))

My question: What the expression

__attribute__((__malloc__))   __attribute__((__alloc_size__(1)))

works or generates? I guess it works like

malloc(sizeof()) 

which allocate the memory based on the sizeof. Why not just use malloc(sizeof()) rather than this completed expression? what is the

__attribute__

? Is it some reserved key word for glib?

gpointer g_slice_alloc0 (gsize block_size) G_GNUC_MALLOC G_GNUC_ALLOC_SIZE(1);

What is the type of the expression? It is not macro or typedef. Is it a function with macro as the function name? Anyone can analysis it for me?

The original link here: https://github.com/GNOME/glib/blob/master/glib/gslice.h


Solution

  • You can read about attributes here: https://gcc.gnu.org/onlinedocs/gcc/Function-Attributes.html

    The malloc one "tells the compiler that a function is malloc-like". The alloc_size "is used to tell the compiler that the function return value points to memory, where the size is given by one or two of the functions parameters."

    It's all for optimizations for the compiler. These attributes do not change how the function works, they just allow the compiler to produce better output.