example1_dynamic_memory_allocation.cpp

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
#include <cstdlib>
#include <iostream>
#include <cstring>

int main() {
    // Allocate memory for an integer
    int* ptr = (int*)malloc(sizeof(int));
    if (ptr == NULL) {
        std::cerr << "Memory allocation failed" << std::endl;
        return EXIT_FAILURE;
    }
    *ptr = 42;
    std::cout << "Allocated integer value: " << *ptr << std::endl;
    free(ptr);

    // Allocate memory for a string
    char* str = (char*)calloc(20, sizeof(char));
    if (str == NULL) {
        std::cerr << "Memory allocation failed" << std::endl;
        return EXIT_FAILURE;
    }
    strcpy(str, "Hello, World!");
    std::cout << "Allocated string: " << str << std::endl;

    // Reallocate memory
    str = (char*)realloc(str, 30 * sizeof(char));
    if (str == NULL) {
        std::cerr << "Memory reallocation failed" << std::endl;
        return EXIT_FAILURE;
    }
    strcat(str, " Extended!");
    std::cout << "Reallocated string: " << str << std::endl;

    free(str);
    return EXIT_SUCCESS;
}
Back to cstdlib