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
37
38
39
40
41
42
43
44
45
46
47
#include <stdio.h>
#include <stdlib.h>

/*
 * This structure is somewhat similar to the maze used in the homework.
 */

typedef struct _Party {
    int    num_people;   // 4 bytes on our platform
    int    start_time;   // 4 bytes on our platform
    char*  name;         // 8 bytes on our platform
    char** daze;         // 8 bytes on our platform
} Party;


int main(int argc, char* argv[]) {
    int num_rows = 4;
    int num_cols = 4;

    // Let's have a party!!!
    Party* party = malloc(sizeof(*party));
    party -> name = "Birthday";  // on data segment
    party -> num_people = 50;
    party -> start_time = 11;
    party -> daze = malloc(sizeof(*daze) * num_rows);
    for(int i = 0; i < num_rows; i++) {
        party -> daze[i] = malloc(sizeof(**daze) * num_cols);
    }

    // Free all heap memory used for this object.

    // 1. Rows (arrays of chars)
    for(int i = 0; i < 4; i++) {
        free(party -> daze[i]);
    }

    // 2. Addresses of rows. -- must be freed after the rows since otherwise,
    //    we wouldn't have the address of each row to free them.
    free(party -> daze);

    // 3. Party itself. -- must be freed after the addresses of rows, since
    //    otherwise, we wouldn't have the address of that array to free it.
    free(party);

    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.