C++ malloc()

The malloc() function in C++ allocates a block of uninitialized memory to a pointer. It is defined in the cstdlib header file.

Example


malloc() Syntax

The syntax of malloc() is:

malloc(size_t size);

Here, size is the size of the memory (in bytes) that we want to allocate.


malloc() Parameters

The malloc() function takes the following parameter:

  • size - an unsigned integral value (casted to size_t) which represents the memory block in bytes

malloc() Return Value

The malloc() function returns:

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

Note: 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

The prototype of malloc() as defined in the cstdlib header file is:

void* malloc(size_t size);

Since the return type is void*, we can type cast it to most other primitive types without issues.


Example 1: C++ malloc()

Output

Initializing values...

Initialized values
1
3
5
7
9

Here, we have used malloc() to allocate 5 blocks of int memory to the ptr pointer. Thus, ptr now acts as an array.

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

Notice that we have type casted the void pointer returned by malloc() to int*.

We then check if the allocation was successful or not using an if statement. If it was not successful, we exit the program.

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

Then, we have used a for loop to initialize the allocated memory blocks with integer values, and another for loop to print those values.

Finally, we have deallocated the memory using the free() function.

free(ptr);

Example 2: C++ malloc() with Size Zero

Output

Address = 0x371530

Here, we have used malloc() to allocate int memory of size 0 to the ptr pointer.

int* ptr = (int*) malloc(0);

Using an if statement, we then check whether malloc() returned a null pointer or if it returned an address.

Finally, we deallocated the memory using free().