Export (0) Print
Expand All
Expand Minimize

malloc

Allocates memory blocks.

void *malloc(
   size_t size 
);

Parameter

size
Bytes to allocate.

Return Value

malloc returns a void pointer to the allocated space, or NULL if there is insufficient memory available. To return a pointer to a type other than void, use a type cast on the return value. The storage space pointed to by the return value is guaranteed to be suitably aligned for storage of any type of object. If size is 0, malloc allocates a zero-length item in the heap and returns a valid pointer to that item. Always check the return from malloc, even if the amount of memory requested is small.

Remarks

The malloc function allocates a memory block of at least size bytes. The block may be larger than size bytes because of space required for alignment and maintenance information.

The startup code uses malloc to allocate storage for the _environ, envp, and argv variables. The following functions and their wide-character counterparts also call malloc:

The C++ _set_new_mode function sets the new handler mode for malloc. The new handler mode indicates whether, on failure, malloc is to call the new handler routine as set by _set_new_handler. By default, malloc does not call the new handler routine on failure to allocate memory. You can override this default behavior so that, when malloc fails to allocate memory, malloc calls the new handler routine in the same way that the new operator does when it fails for the same reason. To override the default, call

_set_new_mode(1)

early in your program, or link with NEWMODE.OBJ.

When the application is linked with a debug version of the C run-time libraries, malloc resolves to _malloc_dbg. For more information about how the heap is managed during the debugging process, see The CRT Debug Heap.

Requirements

Routine Required header Compatibility
malloc <stdlib.h> and <malloc.h> ANSI, Win 98, Win Me, Win NT, Win 2000, Win XP

For additional compatibility information, see Compatibility in the Introduction.

Libraries

All versions of the C run-time libraries.

Example

// crt_malloc.c
/* This program allocates memory with
 * malloc, then frees the memory with free.
 */

#include <stdlib.h>         /* For _MAX_PATH definition */
#include <stdio.h>
#include <malloc.h>

int main( void )
{
   char *string;

   /* Allocate space for a path name */
   string = malloc( _MAX_PATH );

   // In a C++ file, explicitly cast malloc's return.  For example, 
   // string = (char *)malloc( _MAX_PATH );

   if( string == NULL )
      printf( "Insufficient memory available\n" );
   else
   {
      printf( "Memory space allocated for path name\n" );
      free( string );
      printf( "Memory freed\n" );
   }
}

Output

Memory space allocated for path name
Memory freed

See Also

Memory Allocation Routines | calloc | free | realloc | Run-Time Routines and .NET Framework Equivalents

Show:
© 2014 Microsoft