Name
malloc
Synopsis
Allocates a block of memory
#include <stdlib.h> void *malloc
( size_tsize
);
The malloc()
function
obtains a block of memory for the program to use. The argument
specifies the size of the block requested in bytes. The type
size_t
is defined in stdlib.h, usually as unsigned int
.
If successful, malloc()
returns a void pointer to the beginning of the memory block
obtained. Void pointers are converted automatically to another
pointer on assignment, so you do not need to use an explicit cast,
although you may want do so for the sake of clarity. Also, in older
C dialects, malloc()
returned a
pointer to char
, which did
necessitate explicit casts. If no memory block of the requested size
is available, the function returns a null pointer.
Example
struct linelink { char *line; struct linelink *next; }; struct linelink *head = NULL, *tail = NULL; char buffer[2048]; FILE *fp_in; /* ... 0pen input file ... */ while ( NULL != fgets(buffer, sizeof(buffer), fp_in )) { if ( head == NULL ) /* Chain not yet started; add first link */ { head = tail =malloc
( sizeof(struct linelink)); if ( head != NULL ) { head->line =malloc
( strlen( buffer ) + 1 ); if ( head->line != NULL ) { strcpy( head->line, buffer); head->next = NULL; } else fprintf( stderr, "Out of memory\n" ), return -1; } else fprintf( stderr, "Out of memory\n" ), return -1; } else /* Chain already started; add another link ... */
Get C in a Nutshell now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.