Memory Allocation

Memory Allocation — general memory-handling

Functions

Types and Values

extern gboolean g_mem_gc_friendly
struct GMemVTable
extern GMemVTable * glib_mem_profiler_table

Includes

#include <glib.h>

Description

These functions provide support for allocating and freeing memory.

If any call to allocate memory using functions g_new(), g_new0(), g_renew(), g_malloc(), g_malloc0(), g_malloc0_n(), g_realloc(), and g_realloc_n() fails, the application is terminated. This also means that there is no need to check if the call succeeded. On the other hand, the g_try_...() family of functions returns NULL on failure that can be used as a check for unsuccessful memory allocation. The application is not terminated in this case.

As all GLib functions and data structures use g_malloc() internally, unless otherwise specified, any allocation failure will result in the application being terminated.

It's important to match g_malloc() (and wrappers such as g_new()) with g_free(), g_slice_alloc() (and wrappers such as g_slice_new()) with g_slice_free(), plain malloc() with free(), and (if you're using C++) new with delete and new[] with delete[]. Otherwise bad things can happen, since these allocators may use different memory pools (and new/delete call constructors and destructors).

Since GLib 2.46 g_malloc() is hardcoded to always use the system malloc implementation.

Functions

g_new()

#define             g_new(struct_type, n_structs)

Allocates n_structs elements of type struct_type . The returned pointer is cast to a pointer to the given type. If n_structs is 0 it returns NULL. Care is taken to avoid overflow when calculating the size of the allocated block.

Since the returned pointer is already casted to the right type, it is normally unnecessary to cast it explicitly, and doing so might hide memory allocation errors.

Parameters

struct_type

the type of the elements to allocate

 

n_structs

the number of elements to allocate

 

Returns

a pointer to the allocated memory, cast to a pointer to struct_type


g_new0()

#define             g_new0(struct_type, n_structs)

Allocates n_structs elements of type struct_type , initialized to 0's. The returned pointer is cast to a pointer to the given type. If n_structs is 0 it returns NULL. Care is taken to avoid overflow when calculating the size of the allocated block.

Since the returned pointer is already casted to the right type, it is normally unnecessary to cast it explicitly, and doing so might hide memory allocation errors.

Parameters

struct_type

the type of the elements to allocate.

 

n_structs

the number of elements to allocate.

 

Returns

a pointer to the allocated memory, cast to a pointer to struct_type .


g_renew()

#define             g_renew(struct_type, mem, n_structs)

Reallocates the memory pointed to by mem , so that it now has space for n_structs elements of type struct_type . It returns the new address of the memory, which may have been moved. Care is taken to avoid overflow when calculating the size of the allocated block.

Parameters

struct_type

the type of the elements to allocate

 

mem

the currently allocated memory

 

n_structs

the number of elements to allocate

 

Returns

a pointer to the new allocated memory, cast to a pointer to struct_type


g_try_new()

#define             g_try_new(struct_type, n_structs)

Attempts to allocate n_structs elements of type struct_type , and returns NULL on failure. Contrast with g_new(), which aborts the program on failure. The returned pointer is cast to a pointer to the given type. The function returns NULL when n_structs is 0 of if an overflow occurs.

Parameters

struct_type

the type of the elements to allocate

 

n_structs

the number of elements to allocate

 

Returns

a pointer to the allocated memory, cast to a pointer to struct_type

Since: 2.8


g_try_new0()

#define             g_try_new0(struct_type, n_structs)

Attempts to allocate n_structs elements of type struct_type , initialized to 0's, and returns NULL on failure. Contrast with g_new0(), which aborts the program on failure. The returned pointer is cast to a pointer to the given type. The function returns NULL when n_structs is 0 or if an overflow occurs.

Parameters

struct_type

the type of the elements to allocate

 

n_structs

the number of elements to allocate

 

Returns

a pointer to the allocated memory, cast to a pointer to struct_type

Since: 2.8


g_try_renew()

#define             g_try_renew(struct_type, mem, n_structs)

Attempts to reallocate the memory pointed to by mem , so that it now has space for n_structs elements of type struct_type , and returns NULL on failure. Contrast with g_renew(), which aborts the program on failure. It returns the new address of the memory, which may have been moved. The function returns NULL if an overflow occurs.

Parameters

struct_type

the type of the elements to allocate

 

mem

the currently allocated memory

 

n_structs

the number of elements to allocate

 

Returns

a pointer to the new allocated memory, cast to a pointer to struct_type

Since: 2.8


g_malloc ()

gpointer
g_malloc (gsize n_bytes);

Allocates n_bytes bytes of memory. If n_bytes is 0 it returns NULL.

If the allocation fails (because the system is out of memory), the program is terminated.

Parameters

n_bytes

the number of bytes to allocate

 

Returns

a pointer to the allocated memory


g_malloc0 ()

gpointer
g_malloc0 (gsize n_bytes);

Allocates n_bytes bytes of memory, initialized to 0's. If n_bytes is 0 it returns NULL.

If the allocation fails (because the system is out of memory), the program is terminated.

Parameters

n_bytes

the number of bytes to allocate

 

Returns

a pointer to the allocated memory


g_realloc ()

gpointer
g_realloc (gpointer mem,
           gsize n_bytes);

Reallocates the memory pointed to by mem , so that it now has space for n_bytes bytes of memory. It returns the new address of the memory, which may have been moved. mem may be NULL, in which case it's considered to have zero-length. n_bytes may be 0, in which case NULL will be returned and mem will be freed unless it is NULL.

If the allocation fails (because the system is out of memory), the program is terminated.

Parameters

mem

the memory to reallocate.

[nullable]

n_bytes

new size of the memory in bytes

 

Returns

the new address of the allocated memory


g_try_malloc ()

gpointer
g_try_malloc (gsize n_bytes);

Attempts to allocate n_bytes , and returns NULL on failure. Contrast with g_malloc(), which aborts the program on failure.

Parameters

n_bytes

number of bytes to allocate.

 

Returns

the allocated memory, or NULL.


g_try_malloc0 ()

gpointer
g_try_malloc0 (gsize n_bytes);

Attempts to allocate n_bytes , initialized to 0's, and returns NULL on failure. Contrast with g_malloc0(), which aborts the program on failure.

Parameters

n_bytes

number of bytes to allocate

 

Returns

the allocated memory, or NULL

Since: 2.8


g_try_realloc ()

gpointer
g_try_realloc (gpointer mem,
               gsize n_bytes);

Attempts to realloc mem to a new size, n_bytes , and returns NULL on failure. Contrast with g_realloc(), which aborts the program on failure.

If mem is NULL, behaves the same as g_try_malloc().

Parameters

mem

previously-allocated memory, or NULL.

[nullable]

n_bytes

number of bytes to allocate.

 

Returns

the allocated memory, or NULL.


g_malloc_n ()

gpointer
g_malloc_n (gsize n_blocks,
            gsize n_block_bytes);

This function is similar to g_malloc(), allocating (n_blocks * n_block_bytes ) bytes, but care is taken to detect possible overflow during multiplication.

If the allocation fails (because the system is out of memory), the program is terminated.

Parameters

n_blocks

the number of blocks to allocate

 

n_block_bytes

the size of each block in bytes

 

Returns

a pointer to the allocated memory

Since: 2.24


g_malloc0_n ()

gpointer
g_malloc0_n (gsize n_blocks,
             gsize n_block_bytes);

This function is similar to g_malloc0(), allocating (n_blocks * n_block_bytes ) bytes, but care is taken to detect possible overflow during multiplication.

If the allocation fails (because the system is out of memory), the program is terminated.

Parameters

n_blocks

the number of blocks to allocate

 

n_block_bytes

the size of each block in bytes

 

Returns

a pointer to the allocated memory

Since: 2.24


g_realloc_n ()

gpointer
g_realloc_n (gpointer mem,
             gsize n_blocks,
             gsize n_block_bytes);

This function is similar to g_realloc(), allocating (n_blocks * n_block_bytes ) bytes, but care is taken to detect possible overflow during multiplication.

If the allocation fails (because the system is out of memory), the program is terminated.

Parameters

mem

the memory to reallocate.

[nullable]

n_blocks

the number of blocks to allocate

 

n_block_bytes

the size of each block in bytes

 

Returns

the new address of the allocated memory

Since: 2.24


g_try_malloc_n ()

gpointer
g_try_malloc_n (gsize n_blocks,
                gsize n_block_bytes);

This function is similar to g_try_malloc(), allocating (n_blocks * n_block_bytes ) bytes, but care is taken to detect possible overflow during multiplication.

Parameters

n_blocks

the number of blocks to allocate

 

n_block_bytes

the size of each block in bytes

 

Returns

the allocated memory, or NULL.

Since: 2.24


g_try_malloc0_n ()

gpointer
g_try_malloc0_n (gsize n_blocks,
                 gsize n_block_bytes);

This function is similar to g_try_malloc0(), allocating (n_blocks * n_block_bytes ) bytes, but care is taken to detect possible overflow during multiplication.

Parameters

n_blocks

the number of blocks to allocate

 

n_block_bytes

the size of each block in bytes

 

Returns

the allocated memory, or NULL

Since: 2.24


g_try_realloc_n ()

gpointer
g_try_realloc_n (gpointer mem,
                 gsize n_blocks,
                 gsize n_block_bytes);

This function is similar to g_try_realloc(), allocating (n_blocks * n_block_bytes ) bytes, but care is taken to detect possible overflow during multiplication.

Parameters

mem

previously-allocated memory, or NULL.

[nullable]

n_blocks

the number of blocks to allocate

 

n_block_bytes

the size of each block in bytes

 

Returns

the allocated memory, or NULL.

Since: 2.24


g_free ()

void
g_free (gpointer mem);

Frees the memory pointed to by mem .

If mem is NULL it simply returns, so there is no need to check mem against NULL before calling this function.

Parameters

mem

the memory to free.

[nullable]

g_clear_pointer ()

void
g_clear_pointer (gpointer *pp,
                 GDestroyNotify destroy);

Clears a reference to a variable.

pp must not be NULL.

If the reference is NULL then this function does nothing. Otherwise, the variable is destroyed using destroy and the pointer is set to NULL.

A macro is also included that allows this function to be used without pointer casts. This will mask any warnings about incompatible function types or calling conventions, so you must ensure that your destroy function is compatible with being called as GDestroyNotify using the standard calling convention for the platform that GLib was compiled for; otherwise the program will experience undefined behaviour.

[skip]

Parameters

pp

a pointer to a variable, struct member etc. holding a pointer.

[not nullable]

destroy

a function to which a gpointer can be passed, to destroy *pp

 

Since: 2.34


g_steal_pointer ()

gpointer
g_steal_pointer (gpointer pp);

Sets pp to NULL, returning the value that was there before.

Conceptually, this transfers the ownership of the pointer from the referenced variable to the "caller" of the macro (ie: "steals" the reference).

The return value will be properly typed, according to the type of pp .

This can be very useful when combined with g_autoptr() to prevent the return value of a function from being automatically freed. Consider the following example (which only works on GCC and clang):

1
2
3
4
5
6
7
8
9
10
GObject *
create_object (void)
{
  g_autoptr(GObject) obj = g_object_new (G_TYPE_OBJECT, NULL);

  if (early_error_case)
    return NULL;

  return g_steal_pointer (&obj);
}

It can also be used in similar ways for 'out' parameters and is particularly useful for dealing with optional out parameters:

1
2
3
4
5
6
7
8
9
10
11
12
13
gboolean
get_object (GObject **obj_out)
{
  g_autoptr(GObject) obj = g_object_new (G_TYPE_OBJECT, NULL);

  if (early_error_case)
    return FALSE;

  if (obj_out)
    *obj_out = g_steal_pointer (&obj);

  return TRUE;
}

In the above example, the object will be automatically freed in the early error case and also in the case that NULL was given for obj_out .

Parameters

pp

a pointer to a pointer.

[not nullable]

Since: 2.44


g_alloca()

#define             g_alloca(size)

Allocates size bytes on the stack; these bytes will be freed when the current stack frame is cleaned up. This macro essentially just wraps the alloca() function present on most UNIX variants. Thus it provides the same advantages and pitfalls as alloca():

  • alloca() is very fast, as on most systems it's implemented by just adjusting the stack pointer register.

  • It doesn't cause any memory fragmentation, within its scope, separate alloca() blocks just build up and are released together at function end.

  • Allocation sizes have to fit into the current stack frame. For instance in a threaded environment on Linux, the per-thread stack size is limited to 2 Megabytes, so be sparse with alloca() uses.

  • Allocation failure due to insufficient stack space is not indicated with a NULL return like e.g. with malloc(). Instead, most systems probably handle it the same way as out of stack space situations from infinite function recursion, i.e. with a segmentation fault.

  • Allowing size to be specified by an untrusted party would allow for them to trigger a segmentation fault by specifying a large size, leading to a denial of service vulnerability. size must always be entirely under the control of the program.

  • Special care has to be taken when mixing alloca() with GNU C variable sized arrays. Stack space allocated with alloca() in the same scope as a variable sized array will be freed together with the variable sized array upon exit of that scope, and not upon exit of the enclosing function scope.

Parameters

size

number of bytes to allocate.

 

Returns

space for size bytes, allocated on the stack


g_alloca0()

#define             g_alloca0(size)

Wraps g_alloca() and initializes allocated memory to zeroes. If size is 0 it returns NULL.

Note that the size argument will be evaluated multiple times.

Parameters

size

number of bytes to allocate.

 

Returns

space for size bytes, allocated on the stack.

[nullable][transfer full]

Since: 2.72


g_newa()

#define             g_newa(struct_type, n_structs)

Wraps g_alloca() in a more typesafe manner.

As mentioned in the documentation for g_alloca(), n_structs must always be entirely under the control of the program, or you may introduce a denial of service vulnerability. In addition, the multiplication of struct_type by n_structs is not checked, so an overflow may lead to a remote code execution vulnerability.

Parameters

struct_type

Type of memory chunks to be allocated

 

n_structs

Number of chunks to be allocated

 

Returns

Pointer to stack space for n_structs chunks of type struct_type


g_newa0()

#define             g_newa0(struct_type, n_structs)

Wraps g_alloca0() in a more typesafe manner.

Parameters

struct_type

the type of the elements to allocate.

 

n_structs

the number of elements to allocate.

 

Returns

Pointer to stack space for n_structs chunks of type struct_type .

[nullable][transfer full]

Since: 2.72


g_aligned_alloc ()

gpointer
g_aligned_alloc (gsize n_blocks,
                 gsize n_block_bytes,
                 gsize alignment);

This function is similar to g_malloc(), allocating (n_blocks * n_block_bytes ) bytes, but care is taken to align the allocated memory to with the given alignment value. Additionally, it will detect possible overflow during multiplication.

If the allocation fails (because the system is out of memory), the program is terminated.

Aligned memory allocations returned by this function can only be freed using g_aligned_free().

Parameters

n_blocks

the number of blocks to allocate

 

n_block_bytes

the size of each block in bytes

 

alignment

the alignment to be enforced, which must be a positive power of 2 and a multiple of sizeof(void*)

 

Returns

the allocated memory.

[transfer full]

Since: 2.72


g_aligned_alloc0 ()

gpointer
g_aligned_alloc0 (gsize n_blocks,
                  gsize n_block_bytes,
                  gsize alignment);

This function is similar to g_aligned_alloc(), but it will also clear the allocated memory before returning it.

Parameters

n_blocks

the number of blocks to allocate

 

n_block_bytes

the size of each block in bytes

 

alignment

the alignment to be enforced, which must be a positive power of 2 and a multiple of sizeof(void*)

 

Returns

the allocated, cleared memory.

[transfer full]

Since: 2.72


g_aligned_free ()

void
g_aligned_free (gpointer mem);

Frees the memory allocated by g_aligned_alloc().

Parameters

mem

the memory to deallocate.

[nullable]

Since: 2.72


g_memmove()

#define             g_memmove(dest,src,len)

g_memmove has been deprecated since version 2.40 and should not be used in newly-written code.

Just use memmove().

Copies a block of memory len bytes long, from src to dest . The source and destination areas may overlap.

Parameters

dest

the destination address to copy the bytes to.

 

src

the source address to copy the bytes from.

 

len

the number of bytes to copy.

 

g_memdup ()

gpointer
g_memdup (gconstpointer mem,
          guint byte_size);

g_memdup has been deprecated since version 2.68 and should not be used in newly-written code.

Use g_memdup2() instead, as it accepts a gsize argument for byte_size , avoiding the possibility of overflow in a gsizeguint conversion

Allocates byte_size bytes of memory, and copies byte_size bytes into it from mem . If mem is NULL it returns NULL.

Parameters

mem

the memory to copy.

 

byte_size

the number of bytes to copy.

 

Returns

a pointer to the newly-allocated copy of the memory, or NULL if mem is NULL.


g_memdup2 ()

gpointer
g_memdup2 (gconstpointer mem,
           gsize byte_size);

Allocates byte_size bytes of memory, and copies byte_size bytes into it from mem . If mem is NULL it returns NULL.

This replaces g_memdup(), which was prone to integer overflows when converting the argument from a gsize to a guint.

Parameters

mem

the memory to copy.

[nullable]

byte_size

the number of bytes to copy.

 

Returns

a pointer to the newly-allocated copy of the memory, or NULL if mem is NULL.

[nullable]

Since: 2.68


g_mem_set_vtable ()

void
g_mem_set_vtable (GMemVTable *vtable);

g_mem_set_vtable has been deprecated since version 2.46 and should not be used in newly-written code.

This function now does nothing. Use other memory profiling tools instead

This function used to let you override the memory allocation function. However, its use was incompatible with the use of global constructors in GLib and GIO, because those use the GLib allocators before main is reached. Therefore this function is now deprecated and is just a stub.

Parameters

vtable

table of memory allocation routines.

 

g_mem_is_system_malloc ()

gboolean
g_mem_is_system_malloc (void);

g_mem_is_system_malloc has been deprecated since version 2.46 and should not be used in newly-written code.

GLib always uses the system malloc, so this function always returns TRUE.

Checks whether the allocator used by g_malloc() is the system's malloc implementation. If it returns TRUE memory allocated with malloc() can be used interchangeably with memory allocated using g_malloc(). This function is useful for avoiding an extra copy of allocated memory returned by a non-GLib-based API.

Returns

if TRUE, malloc() and g_malloc() can be mixed.


g_mem_profile ()

void
g_mem_profile (void);

g_mem_profile has been deprecated since version 2.46 and should not be used in newly-written code.

Use other memory profiling tools instead

GLib used to support some tools for memory profiling, but this no longer works. There are many other useful tools for memory profiling these days which can be used instead.

Types and Values

g_mem_gc_friendly

extern gboolean g_mem_gc_friendly;

This variable is TRUE if the G_DEBUG environment variable includes the key gc-friendly.


struct GMemVTable

struct GMemVTable {
  gpointer (*malloc)      (gsize    n_bytes);
  gpointer (*realloc)     (gpointer mem,
			   gsize    n_bytes);
  void     (*free)        (gpointer mem);
  /* optional; set to NULL if not used ! */
  gpointer (*calloc)      (gsize    n_blocks,
			   gsize    n_block_bytes);
  gpointer (*try_malloc)  (gsize    n_bytes);
  gpointer (*try_realloc) (gpointer mem,
			   gsize    n_bytes);
};

A set of functions used to perform memory allocation. The same GMemVTable must be used for all allocations in the same program; a call to g_mem_set_vtable(), if it exists, should be prior to any use of GLib.

This functions related to this has been deprecated in 2.46, and no longer work.

Members

malloc ()

function to use for allocating memory.

 

realloc ()

function to use for reallocating memory.

 

free ()

function to use to free memory.

 

calloc ()

function to use for allocating zero-filled memory.

 

try_malloc ()

function to use for allocating memory without a default error handler.

 

try_realloc ()

function to use for reallocating memory without a default error handler.

 

glib_mem_profiler_table

extern GMemVTable *glib_mem_profiler_table;

glib_mem_profiler_table has been deprecated since version 2.46 and should not be used in newly-written code.

Use other memory profiling tools instead

Used to be a GMemVTable containing profiling variants of the memory allocation functions, but this variable shouldn't be modified anymore.