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

int* malloc_ints(int num_ints) {
    // NOTE:  This is violating the "free(…) where you malloc(…) where
    //        possible" rule because this function is intended to
    //        allocate, and serves the same role as malloc(…).
    
    int* new_array = malloc(sizeof(int) * num_ints);
    // NOTE:  Violating the sizeof(expr) rule because this is a generic
    //        function for ints.  There is no meaningful expr.

    free(new_array);
    return new_array;  // <<<< REALLY BAD!!!!!
}

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

    int* array = malloc_ints(3);   // this is now garbage space (deallocated)
    array[0] = 10;
    array[1] = 11;
    array[2] = 12;

    return EXIT_SUCCESS;
}
/* vim: set tabstop=4 shiftwidth=4 fileencoding=utf-8 noexpandtab: */

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