pointersstaticstackdynamically-generated

Freeing pointer content


I doing static and dynamic allocation of 2 differents variables. So, I have the same address for the two pointed-pointer variables.

char **input;
char **output = (char **)malloc(sizeof(char));
input = output;

My questions are the followings : My former statically allocated variable would free char-sized content up ? Undefined behavior ? Of course, when programm is ending the call stack up to its end.


Solution

  • First of al, you should allocate as follows:

    char **output = (char **)malloc(sizeof(char*)*(amount of rows));
    

    as you are making a list of pointers which are 8 bytes while a char is only 1. Either way, whenever you call free on output, you free 1 byte, as you allocated the size of 1 char (which is 1 byte).

    Statically allocated variables are allocated by the compiler and freed whenever out of scope, so you only need to worry about free-ing dynamically allocated memory (pointers)

    input and output point to the same memory space, which has 1 byte reserved on the heap.

    You don't free "char-sized content" you free the amount of memory you allocated in your malloc.