C - false value of integer var [duplicate] - c

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;
}

Related

why does returning the local variable address throws an error but returning the local variable value don't? [duplicate]

This question already has answers here:
Why is a runtime error is produced when we return a local address but not a local variable?
(1 answer)
How to access a local variable from a different function using pointers?
(10 answers)
Closed 10 months ago.
I can not understand, what is the difference between following function bodies
int func(void){
int A = 20;
return A;
}
and
int* func(void){
int A = 20;
return &A;
}
why returning the values does not throw the error of the segmentation fault but returning the address do?
Attempting to target the more specific question asked in follow-up comments on several other answers:
if the address of the local variable after the scope gets deleted then how the value of that address preserved? in case of returning local variable value from the function? this is I can not understand
Returning a value makes a copy of that value, into a storage location provided by the caller. You presumably have something like
void call_func(void) {
int n = func();
printf("%d\n", n);
}
as the function that calls func -- so, when func returns the value of A, that value gets copied into n.
Returning a pointer to A is actually exactly the same: a value is copied into a storage location provided by the caller. Only now the value that gets copied, is the address of the storage location formerly occupied by A.
A local variable with automatic storage duration is not alive after exiting the scope of the function where it is defined. So the returned pointer will be invalid and de-referencing such a pointer invokes undefined behavior.
If you will change the second function the following way
int* func(void){
static int A = 20;
return &A;
}
then returning a pointer to the variable A will be correct because the variable having static storage duration will be alive after exiting the function.
A returned value can be assigned to a variable or discarded. So there is nothing wrong.

Unexpected C behaviour with pointers [duplicate]

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.

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.

Doubts about keyword 'return' in C [duplicate]

This question already has answers here:
Can a local variable's memory be accessed outside its scope?
(20 answers)
Closed 9 years ago.
#include <stdio.h>
int* _pTest1(void) {
int a = 10;
int *_pA = &a;
return _pA;
}
int* _pTest2(int a){
int* _pA = &a;
return _pA;
}
int main()
{
int* _pT = _pTest1();
printf("%d\n", *_pT);
_pT = _pTest2(20);
printf("%d\n", *_pT);
return 0;
}
The Output:
1073831176
20
Why first output isn't 10, but 1073831176? What are the differences between the 'return _pA' in func _pTest1 and the 'return _pA' in func _pTest2?
In both of your _pTest1 and _pTest2 functions, you are returning address of a local variable a, Scope/life of that is only within the function only. Accessing it variable a outside function is undefined behavior.
Note: in both function a is local to function (their memory comes from stack).
You're returning a local object that gets cleaned up when the function terminates.
This is undefined behaviour, anything can happen.
int _pTest1(void) {
int a = 10; // a local object on the stack
int *_pA = &a; // a local pointer to a local object on the stack
return _pA; // returning a local pointer to a local object,
// wrong as the object pointed to may be cleaned up or overwritten.
}
Furthermore, in _pTest1 you probably wanted to return *_pA as at the moment you're returning a pointer even though your function signature indicates you want to return an integer.
Actually you can try a small experiment. See if it makes any difference if you return _pA as a plain pointer (return _pA;) or as a dereferenced pointer (return *_pA;). Don't forget to update the function signature and the types you assign the return of the function to.
You'll find that in the latter case the output will be consistent, whereas in the former by the time you dereference the returned address the value may be long gone.
In your second function you are returning a pointer to an argument that is not local to the function. However a in the function will still have a local address (as arguments in C are always passed by value and a local copy will be made). So returning it is still not guaranteed to result in a meaningful value.
You can prove this with the following code:
int a = 55;
printf("%p\n", &a); // this will have one address e.g. 0xbff51148
int* _pT = _pTest2(a); // _pT points to an address where a local object was held, not reliable
printf("%p\n", _pT); // this will have another address e.g. 0xbff51130

Returning an address of local variable behaviour [duplicate]

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.

Resources