Выделить память под массив


#include <stdlib.h>
void * calloc( size_t n,
size_t size );


The number of array elements to allocate.
The size, in bytes, of one array element.




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.

Note: Because the malloc() implementation uses signed, 32-bit integers to represent the size internally, you can't allocate more than 2 GB in a single allocation. If the size is greater than 2 GB, calloc() indicates an error of ENOMEM.

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.

Возвращаемое значение:

Указатель на начало выделенной памяти. Если возникла ошибка функция возвращает NULL, код ошибки записывается в errno.

Коды ошибок:

Недостаточно памяти.
Успешное завершение.


#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);

Переменные окружения:

Control the way calloc(), malloc(), and realloc() behave if you specify a size of 0 (or a value of 0 for the n argument to calloc()). The V (“System V”) and R (“use the realloc() behavior of Neutrino 6.4.0 and earlier”) columns below indicate how the functions behave if the value of MALLOC_OPTIONS includes that letter:
Function Default V R
calloc( n, 0 ) Non-NULL NULL No effect
malloc( 0 ) Non-NULL NULL No effect
realloc( NULL, 0 ) Non-NULL NULL No effect
realloc( non-NULL, 0 ) Non-NULL NULL NULL
In all the above cases, if the function returns a non-NULL pointer, it's valid only for a corresponding call to free() or realloc().


ANSI, POSIX 1003.1

Точка остановки потока
Обработчик прерываний
Обработчик сигналов
В потоке

Тематические ссылки:

free(), malloc(), realloc(), sbrk()

Предыдущий раздел: Описание API системной библиотеки