Dynamic Memory Allocation in Data Structure using C

In C, you can dynamically allocate memory at runtime using the `malloc()` and `free()` functions. Here is an example of how to use dynamic memory allocation to create and manipulate a linked list:

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

typedef struct Node {
    int data;
    struct Node* next;
} Node;

Node* createNode(int data) {
    Node* node = (Node*) malloc(sizeof(Node)); // Allocate memory for the new node
    node->data = data;
    node->next = NULL;
    return node;
}

void insertNode(Node** head, int data) {
    Node* node = createNode(data);
    node->next = *head;
    *head = node;
}

void printList(Node* head) {
    Node* node = head;
    while (node != NULL) {
        printf("%d ", node->data);
        node = node->next;
    }
}

void freeList(Node* head) {
    Node* node = head;
    while (node != NULL) {
        Node* temp = node;
        node = node->next;
        free(temp);
    }
}

int main() {
    Node* head = NULL; // Initialize an empty list
    insertNode(&head, 1);
    insertNode(&head, 2);
    insertNode(&head, 3);
    printList(head); // Output: 3 2 1
    freeList(head); // Free the memory allocated for the list
    return 0;
}
```

In this example, we define a `Node` struct that contains an integer `data` and a pointer to the next `Node` in the list. We also define a `createNode()` function that creates a new `Node` with the specified `data` by calling `malloc()` to allocate memory for the new `Node`. The `insertNode()` function inserts a new `Node` with the specified `data` at the beginning of the list, and the `printList()` function prints the `data` of each `Node` in the list.

To free the memory allocated for the list, we define a `freeList()` function that iterates through the list and calls `free()` on each `Node` to release the memory allocated for it.

In the `main()` function, we initialize an empty list by setting `head` to `NULL`. We then insert three `Node`s into the list using the `insertNode()` function, with data values of 1, 2, and 3. Finally, we print the list using the `printList()` function, and free the memory allocated for the list using the `freeList()` function.

Note that dynamic memory allocation allows you to create linked lists of any size, but you need to be careful to free the memory allocated for the list when you are done with it, to avoid memory leaks.



About the Author



Silan Software is one of the India's leading provider of offline & online training for Java, Python, AI (Machine Learning, Deep Learning), Data Science, Software Development & many more emerging Technologies.

We provide Academic Training || Industrial Training || Corporate Training || Internship || Java || Python || AI using Python || Data Science etc





 PreviousNext