Skip to main content

Section 27.9 Function to Free a Number

Remember: Whenever you reserve space dynamically (at run-time) using a function such as malloc() it is also your responsibility to free the reserved space once you are done using it.

Activity 27.6.

Next, let’s move the freeing of all allocated space for a number into a function. The function should again work for arbitrarily long numbers, not just for our 3-digit number. Please write a function freeNumber() to which you pass a pointer to the first digit of your number and which frees the space allocated for all of the digits of the number. The function does not need to return anything.

Compile and run the code below in your own C environment.

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

struct digit {
    int num;
    struct digit *next;
};

typedef struct digit digit_t;

digit_t *createDigit(int);
void append(digit_t * start, digit_t * newDigptr);
void printNumber(digit_t *start);

int main(void) {
    digit_t *start, *newDigptr, *tmp;
    start = createDigit(5);
    newDigptr = createDigit(3);
    append(start, newDigptr);
    newDigptr = createDigit(7);
    append(start, newDigptr);

/* print the number */
    //printf("We are storing the number %d%d%d.\n", start->num, start->next->num, start->next->next->num);
    printNumber(start);
    
/* free all allocted space */
    tmp = start->next;
    free(start);
    start = tmp;
    tmp = start->next;
    free(start);
    start = tmp;
    free(start);
    return 0;
}

void printNumber(digit_t *start) {
    digit_t *ptr;
    ptr = start;
    while (ptr !=NULL) {
        printf("%d", ptr->num);
        ptr = ptr->next;
    }
}

digit_t *createDigit(int dig) {
    digit_t *ptr;
    ptr = (digit_t *) malloc(sizeof(digit_t));
    ptr->num = dig;
    ptr->next = NULL;
    return(ptr);
}

void append(digit_t * start, digit_t * newDigptr) {
    digit_t *end = start;
    while(end->next != NULL) {
        end = end->next;
    }
    end->next = newDigptr;
}