COMS 3157 Advanced Programming

Index of 2024-9/code/07

Parent directory
alloc_int.c

alloc_int.c

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

int *alloc_int_array(void) 
{
    // 1) Dangling pointer!

    // int a[10];
    // return a;
 
    // 2) Allocating an array on the heap

    int *p = malloc(sizeof(int) * 10);
    return p;
}

void f(int *p, int x)
{
    *(p + 5) = x;
}

int main()
{
    int *p = alloc_int_array();
    f(p, 500);
    printf("%d\n", p[5]);

    p = NULL;  // memory leak!

    p = alloc_int_array();
    f(p, 501);
    printf("%d\n", p[5]);

    free(p);
}