In a video game, when a new character shows up in a scene, memory is allocated for the character. The game developers made sure the game allocates enough memory for the character before you interacted with it. This allocation happens dynamically during runtime, and it is known as Dynamic Memory Allocation.

"p" is defined as a pointer. Why? Because only Pointers can receive addresses. The malloc function returns an address location.

malloc returns an address, but it does not know the data type the address will represent. Since the pointer "p" is a pointer to an "int" data type, you must typecast the address with "(int *)".

The argument of malloc represents the memory size you want to allocate. Typically, you use the function "sizeOf()" in the malloc argument to represent a size. In the example above, malloc allocated the representation of an "int" data type.

After memory allocation, you can use the pointer as usual. For example, in the snippet below, the pointer is dereferenced and given the value of five (line 2).

free function

The free function deallocates (gives back) previously allocated memory back to the system. You must always deallocate all previously allocated memory. If you do not, it will lead to memory leaks in your application.

The free function syntax is as follows:

free(my_pointer);

The snippet below deallocates the section of memory allocated in our previous example:

Object-Oriented Memory Allocation

The functions malloc and free are often used in the C Programming Language. In C++, the operators new and delete are used instead. The new and delete operators perform the same operation as malloc and free, respectively. However, the new and delete operators are often used to allocate memory for user-defined types such as classes.

new Operator

The new operator does the following operations:

It allocates memory for a User Defined Type object.

It initializes the object. i.e., it calls the class constructor. The initialization ensures that the object is properly initialized before use.

It returns an address to the object allocated. As opposed to malloc, you do not need to typecast the return value.

The syntax for the new operator is as follows:

my_pointer=new User_Defined_Type();

The snippet below shows the allocation of a class object using the "new" operator (line 3)