![]() |
VOOZH | about |
Dynamic memory allocation in C++ refers to performing memory allocation manually by a programmer. Dynamically allocated memory is allocated on Heap, and non-static and local variables get memory allocated on Stack.
Dynamic memory allocation gives programmers the ability to:
Dynamic memory allocation is useful when the required memory size cannot be determined during compile time.
The new operator denotes a request for memory allocation on the Free Store. If sufficient memory is available, a new operator initializes the memory and returns the address of the newly allocated and initialized memory to the pointer variable.
Syntax to use new operator
pointer-variable = new data-type;
Initialize memory: We can also initialize the memory for built-in data types using a new operator. For custom data types, a constructor is required (with the data type as input) for initializing the value. Hereโs an example of the initialization of both data types :
pointer-variable = new data-type(value);
Allocate a block of memory: a new operator is also used to allocate a block(an array) of memory of type data type.
pointer-variable = new data-type[size];
where size(a variable) specifies the number of elements in an array.
๐ dynamic memory allocation
Explanation: The value at *(ptr + 2) is uninitialized and may contain garbage data.
Explanation: The third element of the allocated array (*(ptr + 2)) is initialized to 10.
Explanation:
Explanation: The function returns the address of a local variable that is destroyed after the function ends, so the output is undefined or a garbage value.
Explanation: Memory allocated inside fun persists even after the function ends since it is allocated on the Heap.
Note: Always deallocate memory using
deleteto avoid memory leaks.
delete ptr;
cout << *ptr; // Undefined behavior