C - Freeing pointers inside an array

Viewed 204

I've been trying to have all my pointers that I use malloc to initialize to be inside an array of pointers (or a pointer of pointers, perhaps), so that I can then just go through that array and free each pointer with something like free(ptr_array[i]); and not have to free each one individually.

I believe that this is possible, but I am having some trouble with my code, as the function that is supposed to free everything (and I would rather keep it all in a separate function, if possible) is apparently unable to properly edit the "sub-pointers", and seemingly they're being copied unlike the "main pointer".

Here's the code, which has me stumped:

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

void free_test(int** arg){
    printf("\tReceived arg addr: %p\n",arg);
    printf("\tFreeing arg[0] = %p\n",arg[0]);
    //And, just to MAKE SURE that arg[0] is ver, we do this:
    printf("\tIn-function ver[0] = %d\n",arg[0][0]);
    arg[0][0] = 2;
    printf("\tIn-function ver[0] = %d\n",arg[0][0]);

    free(arg[0]); //This one doesn't work...
    free(arg); //This one works though.
}

int main(){
    int** var;
    int* ver;
    int i;
    printf("ver addr 1: %p\n", ver);
    ver = malloc( sizeof(int) * 3 );
    printf("ver addr 2: %p\n", ver);
    for(i=0;i<3;i++){
        ver[i] = 5*i;
    }
    for(i=0;i<3;i++){
        printf("ver[%d]: %d\t(@ %p)\n",i,ver[i],&(ver[i]));
    }
    printf("var addr 1: %p\n", var);
    var = malloc( sizeof(int *) );
    printf("var addr 2: %p\n", var);
    var[0] = ver;
    printf("var[0] addr = %p\n", var[0]);
    free_test(var);
    printf("ver[0] new value: %d\n", ver[0]);
    //free(var); (free(arg) works in the function, so this one throws an error.)
    printf("So far so good, now break.\n");
    free(ver);
    printf("Didn't break. :(\n");
    return 0;
}

And this is the output it currently gives me:

ver addr 1: 0x8048679
ver addr 2: 0x8b0f008
ver[0]: 0   (@ 0x8b0f008)
ver[1]: 5   (@ 0x8b0f00c)
ver[2]: 10  (@ 0x8b0f010)
var addr 1: 0xad7ff4
var addr 2: 0x8b0f018
var[0] addr = 0x8b0f008
    Received arg addr: 0x8b0f018
    Freeing arg[0] = 0x8b0f008
    In-function ver[0] = 0
    In-function ver[0] = 2
ver[0] new value: 0
So far so good, now break.
Didn't break. :(

I'm not too great with C, and thus any help would be appreciated. Specially since the value of ver[0] is altered inside the function, but not outside, and I'm guessing that will have to do with why free(...) doesn't work too.

Thanks in advance.

4 Answers
Related