Returning pointer to local variable [duplicate] - c

This question already has answers here:
Can a local variable's memory be accessed outside its scope?
(20 answers)
How to access a local variable from a different function using pointers?
(10 answers)
Closed 8 years ago.
What is the problem associated with returning a pointer to a local variable?
And (i don't know if its legal to do this) What is the problem with returning a reference to pointer in main?
ex:
int *p;
p=abc();
where abc would be returning int&
P.S. Sorry if not clear. I am confused too :P

You can syntactically return a pointer to a local variable, but that variable will no longer be valid after the function has returned.

If your code is:
int *abc() {
int n = 3;
return &n;
}
void foo() {
int m = 4;
}
int main() {
int *p;
p=abc();
foo();
printf("%d", *p);
}
then m will probably overwrite n and the result will be 4.

In simple terms, local variables are available only as long as it is in that function is in the function stack, once the function is done, its popped out of the function stack.

Related

C are pointers erased after function call ends? [duplicate]

This question already has answers here:
Can a local variable's memory be accessed outside its scope?
(20 answers)
How to access a local variable from a different function using pointers?
(10 answers)
Closed 2 years ago.
I have learned that whenever a function ends, every local variable declared inside of it is erased. That's why we must use malloc when declaring an array.
But when I think about that again when a function ends what is really erased (in case I defined an array) is the pointer to that array and not the array itself, So we could simply solve the former problem by returning the pointer.
Here is a look at my code, why did it work while my professor said "we must use malloc"?
#include <stdio.h>
int * test ()
{
int arr[3]={4,5,6};
return arr;
}
int main() {
printf("Hello, World!\n");
int *arr=test();
printf("%d",arr[1]);
return 0;
}
Edit: I'm working according to the C99 standard if that does make a difference.
Option 1:
Change it to static
static int arr[3]={4,5,6};
Lifetime of a static variable is throughout the program. So we can always create a local static array and return it.
Option 2:
Create a struct
struct wrapper {
int arr[3];
};
The reason this is, array members of structures are deeply copied.

C - false value of integer var [duplicate]

This question already has answers here:
(Why) is using an uninitialized variable undefined behavior?
(7 answers)
Is reading into uninitialized memory space ALWAYS ill advised?
(6 answers)
Closed 4 years ago.
The output in the following code is really mysterious.
#include <stdio.h>
void funktion(int x) {}
void test() {
int foo;
printf("test = %d\n", foo);
}
int main() {
test();
funktion(5);
test();
return 0;
}
Why will the foo-var initialised with the value of the parameter of funktion()? I don't understand why foo-var is initialised by the function-parameter. I know that I can fix it with a explicit initialisation - but I want to understand the mystery. Thanks!
I've added comments to your main() function that explains why is it so. By the way, you're in undefined behaviour land, and different platforms might yield different results.
int main() {
// no return, no parameter, one local variable of type int.
// This pushes an int on the stack, uninitialized (the local variable).
test();
// Stack pointer is back to where it was.
// no return, one int parameter, no local variables.
// This pushes an int with value=5 on the stack (the parameter).
funktion(5);
// Stack pointer is back to where it was.
// no return, no parameter, one local variable of type int.
// This pushes an int on the stack, uninitialized (the local variable).
// Previous value of that memory comes from funktion() call.
test();
// Stack pointer is back to where it was.
return 0;
}

Is the compiler placing memory on the heap? [duplicate]

This question already has answers here:
Can a local variable's memory be accessed outside its scope?
(20 answers)
Closed 6 years ago.
I don't understand why the following C code works (prints '53'). I thought that int a would be placed on the stack and wiped away as soon as foo() exits. If the compiler is instead placing int a on the heap, is there a way to tell it not to?
#include "stdio.h"
int * foo()
{
int a = 53;
int * b = &a;
return b;
}
int main(void)
{
int * c = foo();
printf("%d\n",*c);
return 0;
}
The integer a is stored on the stack. The reason this works is that function foo returns the address of a and function main dereferences this address to print it before the contents of a's address are overwritten. This program works by accident in this instance. If you want to preserve the value of a for the life of the program you'll either need to apply the static qualifier to a's declaration, or allocate a on the heap.

Not able to understand Let us C static storage class example [duplicate]

This question already has answers here:
Can a local variable's memory be accessed outside its scope?
(20 answers)
Closed 8 years ago.
I am not able to understand an example in Let us C by Yashwant Kanetkar. Here is the code snippet:
main()
{
int *j;
int *fun();
j = fun();
// If we add a function call here, the print statement prints a garbage value.
printf("\n%d",*j);
}
int *fun()
{
int k = 35;
return (&k);
}
Now in the above code, I am not able to understand why having a function call before the printf statement results in printing a garbage value. I have a vague idea that as the returned value points to a memory location in the stack, something goes wrong when another function is called before printing this value. But I am not able to clearly visualize what happens here. Please help.
in your code
int *fun()
{
int k = 35;
return (&k);
}
you're returning the address of a local variable from fun(). Any usage of the return value leads to undefined behaviour.
To explain, once the function fun() finishes execution, there is no existence of k. So , trying to use something like &k is invalid.
Note: Whatever the explanation is provided in that particular book [related to stack flushing or so], is not standardized in c.
int k = 35;
is local to function fun() so once you return from fun() the memory allocated for k is no more valid and you are returning &k(address of that variable) which will lead to undefined behavior

C returning garbage value for length greater than 3 [duplicate]

This question already has answers here:
Since I can't return a local variable, what's the best way to return a string from a C or C++ function?
(8 answers)
Closed 9 years ago.
I have a main function that has to receive a string.
main()
{
char *c = fun();
}
char* fun()
{
char a[] = "hello";
return a;
}
The problem is that if I return string of lenght 3 or less, then everything is good. If I return string of length > 3, then I receive garbage value along with the string. Why is that ?
You return a pointer to a local variable. The variable is stack-allocated, and it is destroyed when the function exits. Using such pointer is undefined behaviour.
char* fun()
{
char a[] = "hello";
return a;
}
Array a has automatic storage duration. At the end of the function the array object a is destroyed. This means the pointer becomes invalid at the exit of the function and any use of it is undefined behavior.
You are returning an automatic variable, which is a big no-no. That it works at all is an accident of the implementation.
The variable a is local to fun(), and so goes out of scope (and out of existence) when you return. The fact that is works for any case is pure luck. You could make a static, or dynamically allocated, or fix it in ohter ways.

Resources