-1

This is not my exact code, but it is like this in essence. I'm trying to create a stack variable in main()

int **x;

that I want to pass to a function foo(int **x, arg1, arg2, ...). On some condition, I'm supposed to dynamically allocate space for x in foo()

x = (int **) malloc(sizeof(int *) * num_elems);

I am also not allocating new space for each int * element, but assigning to it &y, where int y was created in foo().

I got this error when I tried freeing x in main(). I don't understand what it means, but I suspect it might be because I used &y?

EDIT: Also relevant: I got garbage values when I tried accessing the double-dereferenced elements of x.

Kaiser Octavius
  • 157
  • 1
  • 2
  • 8

2 Answers2

1

You are not correctly declared in main function and not correctly defined in foo() function. You have to declare as

In main function

int *x ;
foo(&x);

In foo(int **x,....)

*x =  malloc(sizeof(int) * num_elems);
Mani
  • 17,549
  • 13
  • 79
  • 100
0

Consider this,

void foo()
{
    int y;
    int *x = NULL;
    x = &y;
}

In this case, y is stored in the stack. When foo returns, y will be unavailable (implementation dependant). If you absolutely need to do this, malloc y instead. If you do that, y will be stored on the heap instead.

Anish Ramaswamy
  • 2,326
  • 3
  • 32
  • 63