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

#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

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