Chapter Contents

Previous

Next
malloc

malloc



Allocate Memory

Portability: ISO/ANSI C conforming, UNIX compatible


SYNOPSIS
DESCRIPTION
RETURN VALUE
ERRORS
CAUTION
DIAGNOSTICS
IMPLEMENTATION
EXAMPLE
RELATED FUNCTIONS
SEE ALSO


SYNOPSIS

#include <stdlib.h>

void *malloc(size_t size);


DESCRIPTION

malloc allocates a block of dynamic memory of the size requested by size .


RETURN VALUE

malloc returns the address of the first character of the new block of memory. The allocated block is suitably aligned for storage of any type of data.


ERRORS

User ABEND 1205 or 1206 may occur if memory management data areas are overlaid.


CAUTION

The contents of a memory block on allocation are random.


DIAGNOSTICS

If adequate memory is not available, or if 0 bytes are requested, NULL is returned.


IMPLEMENTATION

Whenever a block is allocated, the amount actually consumed is 16 bytes more than the amount requested (after rounding up to an integral number of doublewords) due to memory management overhead. If more than 288 bytes are requested (after addition of the overhead), the amount is rounded up to an even multiple of 64 bytes.

Storage is always obtained from the operating system in page multiples and only when necessary. Small blocks are kept separate from large blocks to reduce fragmentation.

Under an XA or ESA operating system, memory allocated by malloc can reside above the 16-megabyte line for programs that run in 31-bit addressing mode.

Allocation of a large number of small blocks or of blocks that are slightly larger than half a page may result in significant waste of memory. Use of the pool , palloc , and pfree routines is recommended in such cases.


EXAMPLE

#include <stdlib.h>
#include <stdio.h>
#include <string.h>

char *source, *copy;

main()
{
   source = "A simple line for the malloc example ";

      /* Allocate space for a copy for source. */
   copy = malloc(strlen(source) + 1);

      /* Copy if there is space. */
   if (copy){
      strcpy(copy,source);
      puts(copy);
   }
   else puts("malloc failed to allocate memory for copy".);
}


RELATED FUNCTIONS

pool , realloc , sbrk


SEE ALSO


Chapter Contents

Previous

Next

Top of Page

Copyright © 2001 by SAS Institute Inc., Cary, NC, USA. All rights reserved.