How to Access a Local Variable from a Different Function Using Pointers

How to access a local variable from a different function using pointers?

myArray is a local variable and as thus the pointer is only valid until the end of its scope (which is in this case the containing function getArray) is left. If you access it later you get undefined behavior.

In practice what happens is that the call to printf overwrites the part of the stack used by myArray and it then contains some other data.

To fix your code you need to either declare the array in a scope that lives long enough (the main function in your example) or allocate it on the heap. If you allocate it on the heap you need to free it either manually, or in C++ using RAII.

One alternative I missed (probably even the best one here, provided the array is not too big) is to wrap your array into a struct and thus make it a value type. Then returning it creates a copy which survives the function return. See tp1's answer for details on this.

scope of the variable in c using pointers and functions

It would print 10 if you do this

*q = i

in the called function.

Change the content of that variable whose address is with you in the called function in the local variable q. Don't change the content of the local variable q.

You asked me why? Will explain...

This is what happened when you called the function and printed the value. Well this is not an exhaustive list but this points out the key things that will help in this context.

  1. You got the address of the variable i in p.

  2. Then you pass it to the called function.

  3. Called function now has a local variable whose content is same as that of p.

  4. Now you change the content of that local variable with the address of the global variable i.

  5. Then function ends.

  6. Rest in peace - local variable q. It is dead.

  7. Then you again access *p in main() - meaning you looking for what value there is in the address contained in p.

  8. you get 20.

Is there any other way to get 10?

Well there is

func(&p);

And then you do this

void func(int **q){    
*q = &i;
}

Now you print *p you will get 10.

Know few things clearly, no matter what C is pass by value. Even here also q is a local variable. But now we have the address of p of main()
in q. So when you write *q=&i then you are basically going to the address of p from main() and then write there the address of global variable i. Then you come back. q is again lost. Then you print it - as you change to the original variable (p), the content there is 10.



Code-1

func(p);

then in func()

void func(int *q){
*q = i;
}

Code-2

func(&p);

then in func()

void func(int **q){
*q = &i;
}

Return a pointer that points to a local variable [duplicate]

The following happens:

  1. Within func1, you created the local x variable and initialised it with a value, i.e. x is on the stack now.
  2. You get the address of x and return it to main.
  3. While returning, func1 and its variables x (and, irrelevant to the question, y) are freed, or popped off the stack, i.e. their memory locations are not reserved any more to hold their values. After this, any other part of the program is allowed to use the memory space that was allocated for x within func1, as func1 isn't active any more.
  4. Your first printf call still happens to see the old value of the memory location where x used to be (but this is not guaranteed) and
  5. the second printf call makes it apparent that something else (with the value of 0, such as the first printf's return value as described by R. Joiny) is (or was) using the same address as x within func1.

This article of the C Programming Boot Camp pretty much describes your situation:

A key to understanding the stack is the notion that when a function
exits, all of its variables are popped off of the stack (and hence
lost forever). Thus stack variables are local in nature. This is
related to a concept we saw earlier known as variable scope, or local
vs global variables. A common bug in C programming is attempting to
access a variable that was created on the stack inside some function,
from a place in your program outside of that function (i.e. after that
function has exited).

returning a local variable from function in C [duplicate]

The issue here is that when you create the local variable it is allocated on the stack and is therefore unavailable once the function finishes execution (implementation varies here). The preferable way would be to use malloc() to reserve non-local memory. the danger here is that you have to deallocate (free()) everything you allocated using malloc(), and if you forget, you create a memory leak.

pointers with two similar variables in two different functions

If those functions do not call each other, it's possible that calling one, the address will be x, then if the function returns (and the variable does not escape) and the other function is called, the same x address may be reused; but only if the other variable is not live (reachable) anymore. Whether this may be the case is not clear from your question.

Go has automatic memory management. Unless you touch package unsafe, you should not worry about pointers and addresses, it's safe to take and even to return addresses of local variables. The same memory will not be reused if a variable using that memory is still reachable.

One exception is variables that have 0 size. As per the spec, variables having zero size may or may not have the same address. In practice this causes no trouble as you can't change the value of such variables as they cannot store different values, but you can't assume anything about their memory addresses.



Related Topics



Leave a reply



Submit