117 动态内存管理

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <assert.h>

typedef struct tagHyperIDCard {
    long serialNo;
    char name[32];
    char *phoneNo[];
} HyperIDCard;

int main(int argc, char *argv[])
{
    char *phoneNoA, *phoneNoB;
    // allocate memory for HyperIDCard
    HyperIDCard *id = calloc(1, sizeof(HyperIDCard));
    if (id == NULL)
        return -1;
    // calloc should clear allocated memory
    assert(id->serialNo == 0);
    for (int i = 0; i < sizeof(id->name); i++)
        assert(id->name[i] == 0);
    // re-allocate memory for phone No.
    id = realloc(id,
        1 * sizeof(HyperIDCard) + 4);
    if (id == NULL)
        return -1; 
    // allocate memory for phoneNoA
    if ((phoneNoA = malloc(12)) != NULL) {
        strcpy(phoneNoA, "13100000001");
        id->phoneNo[0] = phoneNoA;
    }   
    else {
        free(id);
        return -1; 
    }
    // add another phone No
    id = realloc(id,
        1 * sizeof(HyperIDCard) + 8); 
    if (id == NULL) {
        free(phoneNoA);
        return -1; 
    }   
    id->serialNo = 200301;
    strcpy(id->name, "x301");
    id->phoneNo[0] = phoneNoA;
    if ((phoneNoB = malloc(12)) != NULL) {
        strcpy(phoneNoB, "13100000002");
        id->phoneNo[1] = phoneNoB;
    }
    else {
        free(phoneNoA);
        free(id);
    }
    // show all phone No
    printf("%06ld\n"
        "%6s\n"
        "%s\n"
        "%s\n"
        "%s\n",
        id->serialNo,
        "------",
        id->name,
        id->phoneNo[0],
        id->phoneNo[1]);
    // release all allocated memory
    free(phoneNoB);
    free(phoneNoA);
    free(id);
    return 0;
}