malloc
Allocates memory blocks.
void*malloc(size_tsize**);**
Routine | Required Header | Compatibility |
malloc | <stdlib.h> and <malloc.h> | ANSI, Win 95, Win NT |
For additional compatibility information, see Compatibility in the Introduction.
Libraries
LIBC.LIB | Single thread static library, retail version |
LIBCMT.LIB | Multithread static library, retail version |
MSVCRT.LIB | Import library for MSVCRT.DLL, retail version |
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.
Parameter
size
Bytes to allocate
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 Using C Run-Time Library Debugging Support.
Example
/* 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>
void main( void )
{
char *string;
/* Allocate space for a path name */
string = 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