// Some code exploring memory functions
// Be aware that this code has compiler warnings and runtime errors
// Marc Chee, April 2019

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

int *createNumber();
int *mallocNumber();

int main (void) {
    int *p = createNumber();
    int *p2 = mallocNumber();
    printf("p is %d and p2 is %d.\n", *p, *p2);
    
    // be sure to free up any allocated memory after we're done with it
    free(p2);
    
    // DANGEROUS! Let's create a memory leak
    // none of these allocations are being freed
    // the pointers that made them are being overwritten,
    // so we can't even find them to free!
    while(1) {
        int *leaky = mallocNumber();
    }
    
    return 0;
}

// a function that will not work!!
// the variable "number" can't exist after this function finishes
int *createNumber() {
    int number = 10;
    return &number;
}

// Allocate memory for a number and return a pointer to them
int *mallocNumber() {
    int *intPointer = malloc(sizeof(int));
    *intPointer = 10;
    return intPointer;
}



Resource created Tuesday 09 April 2019, 12:28:25 AM, last modified Wednesday 10 April 2019, 10:31:49 AM.

file: memory.c


Back to top

COMP1511 19T1 (Programming Fundamentals) is powered by WebCMS3
CRICOS Provider No. 00098G