malloc

 

Description

Allocates a certain number of bytes on heap.

Syntax

void * malloc( size_t nBytes )

Parameters

nBytes
[input] Bytes to allocate. Specifiable maximum number for size_t is (32bit: 4294967295(=2^32-1); 64bit: 9223372036854775807(=2^63-1)).Make sure there are enough memory.

Return

Returns a void pointer to the allocated space, or NULL if there is insufficient memory available.

Examples

EX1

// This is a self contained sample program for the function malloc, 
// To run the program, enter the following command in the Script window:
//   malloc_ex1
// If this runs successfully, the following meassage will be printed:
//    Memory allocation of 200 bytes succeeded.
//
void    malloc_ex1()
{
    char *pstr;
    
    size_t nBytes = 200;
    pstr = (char*)malloc(nBytes); // Demonstration of malloc
    if (pstr != NULL)
    {
        strcpy(pstr,"succeeded");
        printf("Allocating %u bytes of memory %s.\n",nBytes,pstr);
        free(pstr); // free the allocated memory:
    }
    else
        printf("Memory allocation of %u bytes failed. Insufficient memory.\n",nBytes);
}

EX2

// This is a self contained sample program for the function malloc, 
// To run the program, enter the following command in the Script window:
//   malloc_ex2
// If this failed to run, the following error meassage will be printed:
//    Memory allocation of 8589934591 bytes failed. Insufficient memory.
// Marke sure run in 64 bit and there are enough memory.
void    malloc_ex2()
{
    char  *pstr;
    
    size_t nBytes = 0x00000001FFFFFFFFui64; // 8589934591
    pstr = (char*)malloc(nBytes); // Demonstration of malloc
    if (pstr != NULL)
    {
        strcpy(pstr,"succeeded");
        printf("Allocating %I64u bytes of memory %s.\n",nBytes,pstr);
        free(pstr); // free the allocated memory:
    }
    else
        printf("Memory allocation of %I64u bytes failed. Insufficient memory.\n",nBytes);
}

Remark

Allocates a certain number of bytes on heap.

See Also

calloc

header to Include

origin.h

Reference