Previous Page
Next Page

malloc

Allocates a block of memory

#include <stdlib.h>
void *malloc ( size_t size  );

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, fp_in ) )
{
  if ( head == NULL ) /* Chain not yet started; add first link */
  {
    head = malloc( sizeof(struct linelink));
    if ( head != NULL )
    {
      head->line = malloc( strlen( buffer  ) + 1 );
      if ( head->line != NULL )
        strcpy( head->line, buffer );
      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 ... */

See Also

free( ), calloc( ), realloc( )


Previous Page
Next Page