Search code examples
callocation

How to free memory from another file?


I am learning about dynamic memory allocation.

I wrote a few lines to understand how pointers, tables and memory allocation work. I have a malloc function but I don't know where to put the free function?

main.c :

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

    #include "allocation.c"

    int main(void)
    {

        int count = 5;
        int initValue = 2;
        int increment = 3;

        int *result = arithmeticSequence(count, initValue, increment);
        printf("Adresse de mon pointeur : %p\n", result);

        for(int i=0 ; i < count ; i++)
        {
            printf("[%d]", *result);
            result++;
        }
        return 0;
     }

allocation.c :

#include <stdlib.h>

#include "allocation.h"

int *arithmeticSequence(int count, int initValue, int increment)
{
    int *table = NULL;

    table = malloc(count * sizeof(int));

    if(table == NULL)
        exit(1);

    for(int i=0 ; i < count ; i++)
    {
        table[i] = initValue + i * increment;
    }

    printf("Adresse de l'element 0 de la table : %p\n", &table[0]);

    return &table[0];

}

Solution

  • This is the issue of object ownership. Whatever function (or class, module, etc) owns the object (or pointer) is responsible for making sure that it is freed (or destroyed) under all possible conditions, as soon as possible after it is no longer needed. It's also important to make sure that nothing else besides the owner frees it.

    As a programmer, you need to decide what's the best "owner" of each pointer. In this program, the best choice is the main function.