C++ malloc()

The malloc() function in C++ allocates a block of uninitialized memory and returns a void pointer to the first byte of the allocated memory block if the allocation succeeds.

The malloc() function in C++ allocates a block of uninitialized memory and returns a void pointer to the first byte of the allocated memory block if the allocation succeeds.

If the size is zero, the value returned depends on the implementation of the library. It may or may not be a null pointer.

malloc() prototype

void* malloc(size_t size);

This function is defined in <cstdlib> header file.


malloc() Parameters

  • size: An unsigned integral value which represents the memory block in bytes.

malloc() Return value

The malloc() function returns:

  • a pointer to the uninitialized memory block allocated by the function.
  • null pointer if allocation fails.

Example 1: How malloc() function works?

#include <iostream>
#include <cstdlib>
using namespace std;

int main()
{
	int *ptr;
	ptr = (int*) malloc(5*sizeof(int));

	if(!ptr)
	{
		cout << "Memory Allocation Failed";
		exit(1);
	}
	cout << "Initializing values..." << endl << endl;

	for (int i=0; i<5; i++)
	{
		ptr[i] = i*2+1;
	}
	cout << "Initialized values" << endl;

	for (int i=0; i<5; i++)
	{
		/* ptr[i] and *(ptr+i) can be used interchangeably */
		cout << *(ptr+i) << endl;
	}

	free(ptr);
	return 0;
}

When you run the program, the output will be:

Initializing values...

Initialized values
1
3
5
7
9

Example 2: malloc() function with size zero

#include <iostream>
#include <cstdlib>
using namespace std;

int main()
{
	int *ptr = (int*) malloc(0);
	if(ptr==NULL)
	{
		cout << "Null pointer";
	}
	else
	{
		cout << "Address = " << ptr << endl;
	}

	free(ptr);
	return 0;
}

When you run the program, the output will be:

Address = 0x371530