How can I allocate memory and return it (via a pointer-parameter) to the calling function?

Viewed 59279

I have some code in a couple of different functions that looks something like this:

void someFunction (int *data) {
  data = (int *) malloc (sizeof (data));
}

void useData (int *data) {
  printf ("%p", data);
}

int main () {
  int *data = NULL;

  someFunction (data);

  useData (data);

  return 0;
}

someFunction () and useData () are defined in separate modules (*.c files).

The problem is that, while malloc works fine, and the allocated memory is usable in someFunction, the same memory is not available once the function has returned.

An example run of the program can be seen here, with output showing the various memory addresses.

Can someone please explain to me what I am doing wrong here, and how I can get this code to work?


EDIT: So it seems like I need to use double pointers to do this - how would I go about doing the same thing when I actually need to use double pointers? So e.g. data is

int **data = NULL; //used for 2D array

Do I then need to use triple pointers in function calls?

11 Answers

For simplicity, let me call the above single pointer parameter p and the double pointer pp (pointing to p).

In a function, the object that p points to can be changed and the change goes out of the function. However, if p itself is changed, the change does not leave the function.

Unfortunately, malloc by its own nature, typically changes p. That is why the original code does not work. The correction (58) uses the pointer pp pointing to p. in the corrected function, p is changed but pp is not. Thus it worked.

Related