malloc
void *  malloc ( size_t size );
stdlib.h
  cplusplus.com  

Allocate memory block.
  Requests the allocation of a block of size bytes of memory. A pointer to the new block of memory is returned if succesful.
  The dynamic memory should be freed using free once it is no longer needed.

Parameters.

size
size in bytes of the block of memory requested.

Return Value.
  A pointer to the allocated space.
  The type of this pointer is void*. A type cast to the desired type of data pointer should be performed on this returned pointer in order to be used as an ordinary array of a concrete type.
  If the system could not allocate the requested block of memory or if the size requested was 0 a NULL pointer is returned.

Portability.
  Defined in ANSI-C.
  Some systems may apply restrictions on the maximum size for a memory block.

Example.

/* malloc example: string generator*/
#include <stdio.h>
#include <stdlib.h>

main ()
{
  int i,n;
  char * buffer;

  printf ("How long do you want the string? ");
  scanf ("%d", &i);

  buffer = (char*) malloc (i+1);
  if (buffer==NULL) exit (1);

  for (n=0; n<i; n++)
    buffer[n]=rand()%26+'a';
  buffer[i]='\0';

  printf ("Random string: %s\n",buffer);
  free (buffer);

  return 0;
}
This program generates a string of the length specified by the user and fills it with alphabetic characters. The possible length of this string is only limited by the amount of memory available in the system that malloc can allocate.

See also.
  free, calloc, realloc


© The C++ Resources Network, 2000