This question already has answers here:
Can a local variable's memory be accessed outside its scope?
(20 answers)
Closed 3 years ago.
Suppose I have this block of code:
#include <stdio.h>
#include <unistd.h>
int *local_pointer(void)
{
int x = 6;
return &x;
}
void add(void)
{
int a;
a = 4;
a = a + 1;
}
int main()
{
int *result;
result = local_pointer();
printf("int is %d\n", *result);
add();
printf("int is %d\n", *result);
return 0;
}
The output of this code is
int is 6
int is 5
I am confused as to why this is?
If we go through main, the result variable is returned a pointer to x and then when it the pointer is dereferenced the its value is 6 however why does calling the add function make the next printf statement print 5?
Your code has a bug. Your local_pointer function returns a pointer to its x variable. But as soon as that function returns, x no longer exists since it was local. So when you dereference the returned pointer, the results are undefined.
If I had to guess, I'd say that a happens to occupy the memory that x used to occupy. But that's just a guess. The behavior might be due to something else. It might change with compiler options. It might change with a different compiler. Who knows? Fix the bug and the mystery will go away.
The function local_pointer probably (cf. other comments on undefined behaviour) returns a pointer to the stack. So I think you are basically printing the content of the stack. The call to add writes the value 5 to the stack, that's what your second printf is outputing 5.
Related
This question already has answers here:
Can a local variable's memory be accessed outside its scope?
(20 answers)
Closed last year.
I, as student, have been assigned to finish this task, pointer in C. I state the problem and question after the codes. The codes are:
#include <stdio.h>
#include <stdlib.h>
int *value(void){
int i = 3;
return &i;
}
void callme(void) {
int x = 35;
}
int main(void){
int *ip;
ip = value();
printf("*ip == %d\n", *ip);
callme();
printf("*ip == %d\n", *ip);
}
I tried the codes using Code Blocks software. The problem is, when I build and run (The feature in "Code Block" software to just run through the program without any requirement other than the codes itself) the program, it only shows the execution time, while i need is the value of ip according to the question below.
I am still beginner, so bear with me. :-)
The question is "What is the value of ip and explain what happens to ip after each functions have been called?" If able, please answer and explain clearly. If there is anything wrong or not clear, please let me know and comment.
Thanks a lot for the help.
This function
int *value(void){
int i = 3;
return &i;
}
returns a pointer to the local object i with automatic storage duration that will not be alive after exiting the function. So the returned pointer will be invalid.
Dereferencing this pointer in the calls of printf results in undefined behavior.
If you will change the function like
int *value(void){
static int i = 3;
return &i;
}
then the program will be correct though the compiler can issue a warning that the declared variable x in the function callme is not used.
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;
}
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.
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
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Can a local variable's memory be accessed outside its scope?
input:
#include <stdlib.h>
#include <stdio.h>
int func2(void);
int* func1(void);
int func2(void)
{
int* b;
b = func1();
printf("%d", *b);
printf("%d", *b);
printf("%d", *b);
}
int* func1()
{
int a = 13;
return &a;
}
int main()
{
func2();
}
Output:
13 -1077824828 -1077824828
Can someone explain what happened in the stack and OS? Why the result changed from 13 to garbage after getting the value of the pointer?
Sure.
The result will differ between debug and release (clean).
A local variable is EBP-(some offset) if you look at the assembly.
This means, HIGHER IN STACK, as in "further".
This is the address you return.
Normally it would be untouched if the function just returns. In debug build on some compilers, it would be garbaged on purpose to help you catch the dangling pointer error faster. Now, printf call reuses the same addresses in the stack to pass parameters and for its own local variables (it has some). They will be written to the address emptied by func1 return, thus overwriting whatever is pointed by the address you obtained.
Calling printf creates a new stack frame that overwrites the location previously occupied by a.