1

I want to create a function that allocates space for a pointer (from main) to point at. If having the memory allocated in a function, will this memory still be available and safe to use after the that function returns? Here is an example of code:

int foo(int **number)
{
    *number = (int*)malloc(sizeof(int));
}

int main()
{
    int *myVar;
    foo(&myVar);
}

So we see that the memory is allocated in the process of execution of the foo() function.

Will the memory for the myVar variable be allocated in "space" of the foo() function, or in "space" of the main()?

After finishing the execution of the foo(), its memory is being cleared. Will myVar point to the same "space"? Will it be safe to use?

Could it be overwritten by other function, or variable declarations?

alk
  • 69,737
  • 10
  • 105
  • 255
Viorel R
  • 13
  • 2
  • "*that allocates space for a pointer*" well, your code allocates space for an `int`, not *for* pointer. Still, it assigns the address of the memory allocated (for an `int`) *to* a pointer. Accurate wording is essential in this context. – alk Oct 20 '18 at 16:21

2 Answers2

2

No, the memory will not be cleared or deallocated at the end of foo. And yes, your pointer myVar in main will correctly point to the memory you allocated in foo. (You don't need the explicit cast to int *, BTW).

The whole purpose of dynamic memory is to defeat all lifetime rules imposed by "scopes", "functions" and such. The memory allocated by malloc exists independently of any functions and their "spaces". This memory will persist until you yourself manually deallocate it. Dynamic memory (aka freestore, aka heap) persists as long as your program runs.

Note also that you are not allocating "space for a pointer". You are allocating a nameless memory block your pointer will point to. This block exist independently of any pointers. You can have a hundred pointers pointing to the same block, or you can have none at all.

AnT stands with Russia
  • 312,472
  • 42
  • 525
  • 765
0

What's specific to a function is a local variable which can be a pointer itself. These variables exist on the stack and are cleaned up with the scope of the function ie - when the function exits.

But when memory is allocated using malloc/calloc, the area alloted is in the heap which is agnostic to the lifetime of functions. A pointer to this memory area is returned which is a variable in scope of some function or maybe main itself. In your case - int *myVar.

Hence as long as your process runs the pointer obtained(using malloc/calloc) anywhere would be valid(unless you free it deliberately).

To ensure you have the memory area accessible, you need to use pass by reference or return the pointer itself.

Rajeev Ranjan
  • 3,588
  • 6
  • 28
  • 52
  • "*you need to use pass by reference*" C is always only and ever doing "*pass by value*". It does not know pass by reference (as opposed to C++). – alk Oct 20 '18 at 17:01