0
votes

Okay I go through 2 layers of functions fun1 calls func2 calls func3 . I pass a pointer all the way down using basically int *ptr, at the lowest "level" of the call stack I also have another function that dynamically allocates memory for an int array. At the top level (func1 level) I always get null back for the passed pointer. I have traced down to func3 and the allocated memory is being filled with values, but as the call stack unwinds func3 -> func2 suddenly the pointer just goes away (0x0000_0000)? I don't understand at func3 level I basically say ptr = allocate_ptr_array, but from that return it goes to NULL! Even though I didn't free the memory, what in the world is going on? I know my question is confusing. I have watched this happen in the debugger though

3
I remember bumping into this before myself and it can be fairly hard to realize why its happening. Good question, could use a less general title though. - Anton

3 Answers

6
votes

The pointer is basically passed by value. You need to pass pointer to pointer (int **p) to get the memory allocated back in outer function.

function1(int *p)
{
 p = //allocate memory using malloc
}

function2(int **p)
{
 *p = //allocate memory using malloc
}

function3()
{
 int *p;
 function1(p); 
// in this case pointer is passed by value. 
//The memory allocated will not be available in p after the function call function1.

int **p;
function2(&p); 
//in this case pointer to pointer p has been passed.
// P will have the memory allocated even after 
//the function call function1
}

}

2
votes

To illuminate aJ's (completely correct) answer with some code:

void func1(void)
{
    int *int_array;

    func2(&int_array);

    /* Some stuff using int_array[0] etc */

    /* ... */

    free(int_array);
}

void func2(int **a)
{
     /* ... stuff ... */

     func3(a);

     /* .... stuff ... */
}

void func3(int **a)
{
    (*a) = malloc(N * sizeof **a);
}
0
votes

Here is a good example for future reference bye other people. It makes sense after implementation and thanks to these guys.

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

void func3(int **ptr)
{
    int i;
    (*ptr) = (int *)malloc(25*sizeof(int));

    for (i=0; i < 25; i++) (**ptr) = i;
    printf("func3: %d\n",ptr);
}

void func2(int **ptr)
{
    func3(ptr);
    printf("func2: %d\n", ptr);
}
void func1(void)
{
    int *ptr;
    printf("ptr before: %d\n", ptr);
    func2(&ptr);
    printf("ptr after: %d\n", ptr);
}

void func4(int **ptr)
{
    static int stuff[25];
    printf("stuff: %d\n",stuff);
    *ptr = stuff;
}

int main(void)
{
    int *painter;
    func1();
    func4(&painter);
    printf("painter: %d\n", painter);
    return 0;
}