GLib – 2.0: Memory Allocation
Description: Reference for GLib-2.0: Memory Allocation

#### Memory Allocation

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.

## Struct Allocations

- `g_new()`
- `g_new0()`
- `g_renew()`
- `g_try_new()`
- `g_try_new0()`
- `g_try_renew()`

## Block Allocations

- `g_malloc()`
- `g_malloc0()`
- `g_realloc()`
- `g_try_malloc()`
- `g_try_malloc0()`
- `g_try_realloc()`
- `g_malloc_n()`
- `g_malloc0_n()`
- `g_realloc_n()`
- `g_try_malloc_n()`
- `g_try_malloc0_n()`
- `g_try_realloc_n()`

## Free Functions

- `g_free()`
- `g_free_sized()`
- `g_clear_pointer()`
- `g_steal_pointer()`

In addition, the `g_mem_gc_friendly` exported variable will be true if GLib has been run with `G_DEBUG=gc-friendly`. If so, memory to be freed will be cleared to zero before being freed.

## Stack Allocations

- `g_alloca()`
- `g_alloca0()`
- `g_newa()`
- `g_newa0()`

## Aligned Allocations

- `g_aligned_alloc()`
- `g_aligned_alloc0()`
- `g_aligned_free()`
- `g_aligned_free_sized()`

## Copies and Moves

- `g_memmove()`
- `g_memdup2()`

## Deprecated API

- `g_memdup()`
- `GMemVTable`
- `g_mem_set_vtable()`
- `g_mem_is_system_malloc()`
- `glib_mem_profiler_table` exported variable
- `g_mem_profile()`