COMS 3157 Advanced Programming

Index of 2025-9/code/07

Parent directory
alloc_int.c
main.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);
}

main.c

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

#include "alloc.h"

// Exercise:
//
// Finish this program. 
//
// - files: Makefile, main.c, alloc.c, alloc.h
// - executable name is "main"
// - make sure to check "valgrind --leak-check=full ./main"
//
int main()
{
    // allocate an array of 5 ints and fill it with 100, 101, ..., 104
    int *p1 = alloc_and_fill(100, 5);

    // print_array takes a pointer and # of elements, 
    // and prints them in a single line separated by space
    print_array(p1, 5);

    int *p2 = alloc_and_fill(200, 15);

    print_array(p1, 15);

    // TODO: use valgrind to fix bugs and leaks, if any
}