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

// MALLOC PITFALLS AND THINGS TO BE AWARE OF

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

    int* array = malloc(3 * sizeof(*array));

    // array might be NULL.  Most instructors will tell you to check the
    // return value of NULL.  It will be NULL if the system doesn't have
    // enough memory or something else is very, very wrong.
    
    // This is what most instructors will tell you to do.
    
    if(array == NULL) {
        fprintf(stderr, "malloc(…) failed.\n");
        return EXIT_FAILURE;
    }

    // How can you get 100% test coverage if you don't know how to force
    // malloc(…) to be NULL?

    int return_code = EXIT_FAILURE;
    int* array_2 = malloc(3 * sizeof(*array));
    if(array_2 != NULL) {
        // Do some stuff
        return_code = EXIT_SUCCESS;
    }

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

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