Allocate space for an array
#include <stdlib.h> void* calloc ( size_t n, size_t size );
libc
Use the -l c option to qcc to link against this library. This library is usually included automatically.
The calloc() function allocates space from the heap for an array of n objects, each of size bytes, and initializes them to 0. Use free() or realloc() to free the block of memory.
If n or 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, calloc() returns a NULL pointer. This environment variable also affects malloc() and realloc(). This is known as the System V behavior.
The function checks for integer wraparound when calculating n*size and returns an error if wraparound occurs. This saves you from having to write manual checks. Thus, the maximum amount of memory you can allocate for an array is (size_t)−1, or SIZE_MAX.
A pointer to the start of the allocated memory, or NULL if an error occurred (errno is set).
#include <stdlib.h> #include <stdio.h> int main( void ) { char* buffer; buffer = (char* )calloc( 80, sizeof(char) ); if( buffer == NULL ) { printf( "Can't allocate memory for buffer!\n" ); return EXIT_FAILURE; } free( buffer ); return EXIT_SUCCESS; }
See the entry for mallopt().
Safety: | |
---|---|
Cancellation point | No |
Interrupt handler | No |
Signal handler | No |
Thread | Yes |