Skip to content
Snippets Groups Projects
Commit 52654272 authored by Mactavish's avatar Mactavish
Browse files

add dynamic memory management

parent bcfdfeb0
No related branches found
No related tags found
No related merge requests found
......@@ -384,6 +384,75 @@ int main(void)
}
```
### Dynamic Memory Allocation
C supports function for heap management:
- `malloc`: allocate a block of **uninitialized** memory
- `calloc`: allocate a block of **zeroed** memory
- `free`: free previously allocated block of memory
- `realloc`: change size of previously allocated block (**careful** - it might move!)
The following is an example of binary tree implementation using dynamic memory allocation:
```c
#include <stdio.h>
#include <stdlib.h>
struct TreeNode {
int val;
struct TreeNode* left;
struct TreeNode* right;
};
struct TreeNode* create_node(int val) {
struct TreeNode* node = (struct TreeNode*) malloc(sizeof(struct TreeNode));
node->val = val;
node->left = NULL;
node->right = NULL;
return node;
}
// Traverse the tree in-order and print the values
void traverse(struct TreeNode* node) {
if (node == NULL) {
return;
}
traverse(node->left);
printf("%d ", node->val);
traverse(node->right);
}
struct TreeNode* insert(struct TreeNode* root, int val) {
if (root == NULL) {
return create_node(val);
}
if (val < root->val) {
root->left = insert(root->left, val);
} else {
root->right = insert(root->right, val);
}
return root;
}
int main() {
struct TreeNode* root = NULL;
root = insert(root, 5);
root = insert(root, 3);
root = insert(root, 7);
root = insert(root, 2);
root = insert(root, 4);
root = insert(root, 6);
root = insert(root, 8);
traverse(root);
return 0;
}
```
> There is a problem for this program, can you find out?
## C Compilation Process
Unlike other interpreted programming languages, we use compilers to compile C written programs.
......
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Please register or to comment