malloc()

Updated: April 19, 2023

Allocate memory

Synopsis:

#include <stdlib.h>

void* malloc( size_t size );

Arguments:

size
The number of bytes to allocate.

Library:

libc

Use the -l c option to qcc to link against this library. This library is usually included automatically.

Description:

The malloc() function allocates a buffer of size bytes. Use free() or realloc() to free the block of memory.

If size is zero, the default behavior is to return a non-NULL pointer that's valid only to a corresponding call to free() or realloc(). Don't assume that this pointer points to any valid memory. You can control this behavior via the MALLOC_OPTIONS environmental variable; if the value of MALLOC_OPTIONS contains a V, malloc() returns a NULL pointer. This environment variable also affects calloc() and realloc(). This is known as the “System V” behavior. For more information, see the entry for mallopt().

Note: If there isn't a free block of memory that's large enough to satisfy the request, the memory allocator uses mmap() to get memory from the system. The _amblksiz global variable (defined in <stdlib.h>) specifies the number of bytes that the allocator gets from the system. You can also use the mallopt() function to control how the system allocates memory.

The heap is protected by such security measures as address space layout randomization (ASLR), which randomizes the stack start address and code locations in executables and libraries, and heap cookies.

Returns:

A pointer to the start of the allocated memory, or NULL if an error occurred (errno is set).

Errors:

ENOMEM
Not enough memory.

Examples:

#include <stdlib.h>

int main( void )
{
    char* buffer;

    buffer = (char* )malloc( 80 );
    if( buffer != NULL ) {
        /* do something with the buffer */
        …

        free( buffer );
    }
    
    return EXIT_SUCCESS;
}

Environment variables:

You can modify the allocator characteristics by calling mallopt() or by setting environment variables. You can control:

For more information, see the entry for mallopt() and Dynamic memory management in the “Working with Memory” chapter of the QNX Neutrino Programmer's Guide.

Classification:

ANSI, POSIX 1003.1

Safety:  
Cancellation point No
Interrupt handler No
Signal handler No
Thread Yes

Caveats:

Don't use brk() and sbrk() with any other memory functions (such as malloc(), mmap(), and free()). The brk() function assumes that the heap is contiguous; in QNX Neutrino, memory is returned to the system by the heap, causing the heap to become sparse. The QNX Neutrino malloc() function is based on mmap(), and not on brk().

In QNX 4, nothing is allocated when you malloc() 0 bytes. Be careful if your code is ported between QNX 4 and later QNX operating systems.