# Dynamic memory allocation

## **Dynamic Memory Allocation Functions**

**1. `malloc`**

`malloc` (memory allocation) allocates a specified number of bytes of memory and returns a pointer to the beginning of the allocated block.

**Syntax:**

```c
void *malloc(size_t size);
```

* **`size`**: Number of bytes to allocate.

**Example:**

```c
#include <stdio.h>
#include <stdlib.h>

int main() {
    int *arr = (int *)malloc(5 * sizeof(int));  // Allocate memory for 5 integers
    
    if (arr == NULL) {
        printf("Memory allocation failed\n");
        return 1;
    }
    
    // Use the allocated memory
    for (int i = 0; i < 5; i++) {
        arr[i] = i * 10;
        printf("%d ", arr[i]);  // Outputs: 0 10 20 30 40
    }
    
    free(arr);  // Free the allocated memory
    
    return 0;
}
```

**2. `calloc`**

`calloc` (contiguous allocation) allocates memory for an array of elements, initializes all bytes to zero, and returns a pointer.

**Syntax:**

```c
void *calloc(size_t num, size_t size);
```

* **`num`**: Number of elements.
* **`size`**: Size of each element in bytes.

**Example:**

```c
#include <stdio.h>
#include <stdlib.h>

int main() {
    int *arr = (int *)calloc(5, sizeof(int));  // Allocate and initialize memory for 5 integers
    
    if (arr == NULL) {
        printf("Memory allocation failed\n");
        return 1;
    }
    
    // Use the allocated memory
    for (int i = 0; i < 5; i++) {
        printf("%d ", arr[i]);  // Outputs: 0 0 0 0 0 (all initialized to 0)
    }
    
    free(arr);  // Free the allocated memory
    
    return 0;
}
```

**3. `realloc`**

`realloc` (reallocation) changes the size of a previously allocated memory block. It may move the block to a new location.

**Syntax:**

```c
void *realloc(void *ptr, size_t newSize);
```

* **`ptr`**: Pointer to the previously allocated memory block.
* **`newSize`**: New size in bytes.

**Example:**

```c
#include <stdio.h>
#include <stdlib.h>

int main() {
    int *arr = (int *)malloc(5 * sizeof(int));  // Allocate memory for 5 integers
    
    if (arr == NULL) {
        printf("Memory allocation failed\n");
        return 1;
    }
    
    for (int i = 0; i < 5; i++) {
        arr[i] = i * 10;
    }
    
    // Resize the memory block to hold 10 integers
    arr = (int *)realloc(arr, 10 * sizeof(int));
    
    if (arr == NULL) {
        printf("Memory reallocation failed\n");
        return 1;
    }
    
    for (int i = 5; i < 10; i++) {
        arr[i] = i * 10;
    }
    
    // Use the resized memory
    for (int i = 0; i < 10; i++) {
        printf("%d ", arr[i]);  // Outputs: 0 10 20 30 40 50 60 70 80 90
    }
    
    free(arr);  // Free the allocated memory
    
    return 0;
}
```

**4. `free`**

`free` releases a block of memory previously allocated by `malloc`, `calloc`, or `realloc`.

**Syntax:**

```c
void free(void *ptr);
```

* **`ptr`**: Pointer to the memory block to be freed.

**Example:**

```c
#include <stdio.h>
#include <stdlib.h>

int main() {
    int *arr = (int *)malloc(5 * sizeof(int));  // Allocate memory for 5 integers
    
    if (arr == NULL) {
        printf("Memory allocation failed\n");
        return 1;
    }
    
    // Free the allocated memory
    free(arr);
    
    return 0;
}
```

***

#### **Dynamic Arrays**

Dynamic arrays are arrays whose size can be adjusted at runtime using the above memory allocation functions.

**Example: Dynamic Array Creation and Resizing**

```c
#include <stdio.h>
#include <stdlib.h>

int main() {
    int *arr = (int *)malloc(3 * sizeof(int));  // Allocate memory for 3 integers
    
    if (arr == NULL) {
        printf("Memory allocation failed\n");
        return 1;
    }
    
    // Initialize the array
    for (int i = 0; i < 3; i++) {
        arr[i] = i + 1;
    }
    
    // Resize the array to hold 6 integers
    arr = (int *)realloc(arr, 6 * sizeof(int));
    
    if (arr == NULL) {
        printf("Memory reallocation failed\n");
        return 1;
    }
    
    // Initialize the new elements
    for (int i = 3; i < 6; i++) {
        arr[i] = i + 1;
    }
    
    // Use the dynamic array
    for (int i = 0; i < 6; i++) {
        printf("%d ", arr[i]);  // Outputs: 1 2 3 4 5 6
    }
    
    free(arr);  // Free the allocated memory
    
    return 0;
}
```

**Explanation:**

* **Allocate:** `malloc` allocates initial memory for 3 integers.
* **Resize:** `realloc` increases the array size to 6 integers.
* **Use:** Initialize and access the dynamic array elements.
* **Free:** `free` releases the memory when done.

***

#### **Summary**

* **`malloc`**: Allocates memory.
* **`calloc`**: Allocates and initializes memory.
* **`realloc`**: Resizes previously allocated memory.
* **`free`**: Releases allocated memory.
* **Dynamic Arrays**: Created and resized at runtime using these functions.


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://cs.d19.in/dynamic-memory-allocation.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
