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
#include <stdio.h>
#include <stdlib.h>

int main(int argc, char* argv[]) {

    int n = 2;

    // Allocate memory on HEAP  (i.e., reserve space)
    int* array = malloc(n * sizeof(*array));
                // n int's x sizeof(*array) bytes / int
                //  == 2 int's x sizeof(int) bytes / int
                //  == 2 int's x 4 bytes / int
                //  == 8 bytes
    array[0] = 10;
    array[1] = 12;

    // Deallocate memory on heap that was allocated at line 9 (i.e., give it back after use)
    //free(array);  // Do this in same scope as malloc(…) that allocated array, *if possible*

    array[0] = 11;
    printf("array[0] = %d\n", array[0]); // BAD!!!!!!!!!!!!!
    
    return EXIT_SUCCESS;
}
/* vim: set tabstop=4 shiftwidth=4 fileencoding=utf-8 noexpandtab: */

© Copyright 2019 Alexander J. Quinn         This content is protected and may not be shared, uploaded, or distributed.