Created: 2023-01-15 18:38
Status: #concept
Subject: Programming
Tags: C Memory Memory Address Functions Garbage stdlib.h Linked List
Dynamic Memory Allocation
Description
- Dynamic Memory Allocation is the process of allocating Byte Memory from the Memory Heap in order to be used by the program during runtime.
C
- This allow us to return variable length Strings or Arrays from Functions.
- The functions related to Memory Allocation are found in the
<stdlib.h>
Library. - The Memory Allocation functions return a
void *
which is a Pointer that can be assigned to ANY C Data Type.
What does
malloc
do? What is the syntax?
void *malloc(size_t size)
- It allocates a block of memory, with a specified size, in Bytes, but doesn’t initialize it.
- Returns a void Pointer
void *
which can be assigned to Pointer Variables, IF SUCCESSFUL. - Otherwise, returns a
NULL
pointer with a Memory Address of00000000
, IF FAILURE.
void calloc(size_t nitems, size_t size)
- This function allocates a block of memory, and clears it (Initializes each Memory Address with
0
.
What function lets us deallocate memory? Why is it important to do so?
- We have to deallocate unused Memory (known as Garbage in order to prevent Memory Leaks or
NULL
Return Values frommalloc
orcalloc
.
void free(void *ptr);
- Deallocates the memory block pointed by
*ptr
p = malloc(...);
q = malloc(...);
free(p); // frees or 'collects' the memory block pointed by p
p = q;
#include <stdlib.h>
#include <stdio.h>
char *concat(const char *str1, const char *str2)
{
char *result = malloc(strlen(str1) + strlen(str2) + 1);
if (result == NULL) // no memory error handler
{
printf("Error: malloc failed.");
exit(EXIT_FAILURE);
}
strcpy(result, str1);
strcat(result, str2);
return result;
}
int main(void)
{
char *str1 = "poggers ", *str2 = "champ!";
puts(concat(str1, str2));
// poggers champ!
}
Idiom: Conditional Comparison with NULL
- Since
NULL
is00000000
and any non-null Pointer evaluates to non-zero, NULL =False
non-null Address =True
. - This will be important in traversing through Linked Lists.
if (p == NULL) ...
if (!p) ... // equivalent
if (p != NULL) ...
if (p) ... // equivalent
// It's better to do explicit comparison with NULL due to compatibility
References
- C Programming, A Modern Approach, 2nd Edition, Chapter 17.1