Which keyword is used to allocate dynamic memory in C++?a)mallocb)call...
The new keyword is used to dynamically allocate memory in C++.
View all questions of this test
Which keyword is used to allocate dynamic memory in C++?a)mallocb)call...
Dynamic Memory Allocation in C
Dynamic memory allocation is a feature in the C programming language that allows programmers to allocate memory dynamically at runtime. This is particularly useful when the amount of memory required is not known in advance or when memory needs to be allocated and deallocated as needed.
Keyword for Dynamic Memory Allocation
The keyword used to allocate dynamic memory in C is "malloc". Here's a detailed explanation of the keyword and its usage:
1. malloc()
The malloc() function in C is used to dynamically allocate a block of memory on the heap. It stands for "memory allocation". It takes the number of bytes as an argument and returns a pointer to the allocated memory. The general syntax for using malloc is:
```c
ptr = (cast-type*) malloc(size);
```
Where:
- `ptr` is the pointer to the allocated memory block.
- `cast-type` is the type of data to be allocated.
- `size` is the number of bytes to be allocated.
Example:
```c
int* ptr;
ptr = (int*) malloc(5 * sizeof(int));
```
In this example, malloc is used to allocate memory for an array of 5 integers. The sizeof(int) is used to determine the size of each integer element. The pointer `ptr` now points to the allocated memory.
2. calloc()
The calloc() function is another keyword used for dynamic memory allocation in C. It is similar to malloc(), but it initializes the allocated memory block to zero. The general syntax for using calloc is:
```c
ptr = (cast-type*) calloc(n, size);
```
Where:
- `ptr` is the pointer to the allocated memory block.
- `cast-type` is the type of data to be allocated.
- `n` is the number of elements to be allocated.
- `size` is the size of each element.
Example:
```c
int* ptr;
ptr = (int*) calloc(5, sizeof(int));
```
In this example, calloc is used to allocate memory for an array of 5 integers. The pointer `ptr` now points to the allocated memory, which is initialized to zero.
3. free()
After dynamically allocating memory using malloc() or calloc(), it is essential to deallocate the memory once it is no longer needed. This is done using the free() function. The general syntax for using free is:
```c
free(ptr);
```
Where `ptr` is the pointer to the memory block that needs to be deallocated.
Summary
In summary, the keyword used to allocate dynamic memory in C is malloc(). It is used in conjunction with the free() function to allocate and deallocate memory dynamically at runtime. The calloc() function can also be used for dynamic memory allocation, but it initializes the allocated memory to zero.