COMS 3157 Advanced Programming

Index of 2024-1/code/07

Parent directory
alloc_int.c

alloc_int.c

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

int *alloc_int(void) 
{
    // 1) Dangling pointer!
    //
    // int i = 5;
    // return &i; 

    // 2) Allocating 4 bytes on the heap to use it as a single int
    //
    // int *p = malloc(sizeof(int));
    // *p = 6;

    // 3) Allocating 40 bytes to use it as an array of 10 ints
    //
    int *p = malloc(sizeof(int) * 10);
    *p = 8;
    return p;
}

void f(int *p)
{
    ++*p;
}

int main()
{
    int *p = alloc_int();
    f(p);
    printf("%d\n", *p);

    p = NULL;  // memory leak!

    p = alloc_int();
    p[5] = 500;
    printf("%d\n", *(p + 5));
    free(p);
}