C++ cstdlib malloc


The C++ <cstdlib> malloc function allocate memory in the heap.This means the function allocate memory during run-time.The declaration of the function is shown below.

Link: what is run-time?

void *malloc(size_t size);

Parameters:
size_t -The number of bytes the memory is to be allocated.

Return type
void* -A pointer to the memory allocated.

Some points to note:

i)The memory allocated is ‘void’ type.To use the memory for other data type cast the memory to the respective type.

ii)If the argument passed is 0 the behavior is implementation-defined.

iii)If the allocation of the memory failed NULL is returned.

Link : C++ cstdlib free

Code example

char *c=(char*)malloc( sizeof(char)*5 ); ///allocate memory that can store 5 characters,and the returned pointer is casted to char* type

memcpy( c , “New or” , 4 ); ///Copies four characters from the second string argument

c[4]=’\0′; ///C style string requires that the last character is a NULL(‘\0’) character

cout<< c ;

free( c ); ///frees the memory pointed by ‘c’

Output

New





A more exhaustive code example is given below.

#include <iostream>
#include <cstdlib>

using namespace std ;

int main( )
{
int *imem=(int*)malloc( sizeof(int)*2 ); ///allocate memory to store 2 integers

if( imem!=NULL )
{
*imem=10101 ;
*(imem+1)=9090 ;
}
else
cout<< “Memory allocation failed”;

cout<< *imem << ” ” << *(imem+1) ;

free( imem ); ///do not forget!

cin.get( );
return 0;
}

Output

10101 9090

Calling the ‘free’ function is must to prevent leakage of memory.

You must prefer C++ style of dynamic memory allocation instead of this C style memory allocation using the ‘malloc’ function.The C++ style offer more advantages than the counterpart C style allocation.

Link : C++ dynamic memory allocation