malloc()
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().
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:
- how memory is cached by the allocator, and when it's released back to the system
- the exact distribution of sizes used to create small bands of memory and the threshold at which the smaller blocks end and the list-based allocator for larger blocks begins
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:
| 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.
