Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 9 years ago.
Improve this question
I'm preparing for a job interview.
My c program is :
void foo(void)
{
int a;
printf("%d\n",a);
}
void bar(void)
{
int a=42;
}
void main(void)
{
bar();
foo();
}
I'm getting the output as : 42
But how? I thought it would be some garbage value .
How the concept of execution stack or activation frame is applied in this?
Please explain
Thanks
a is not initialized in function foo. Printing an uninitialized variable invokes undefined behavior.
In this case you may get anything, either expected or unexpected result. On my compiler the output is
4203214
The result may vary compiler to compiler, even different versions of same compiler could give you different results.
But one of the possible reason that you are getting 42 is because auto variables are often allocated on an execution stack. After the call of bar, 42 is placed on execution stack. This value remains in stack undisturbed. When foo is called, it might read that stack space for a and prints 42.
Try to optimize your code (compile with -o), you may get some different value for a.
The call to bar() puts the value 42 on the stack. It is still there when foo() is called.
The stack frames of bar() and foo() are likely identical, or a least similar enough, so that the a in foo() keeps the value 42.
Of course, this is not guaranteed, and is Undefined Behavior. But rather than simply dismissing such questions, as is often done, for debugging code one often needs some understanding.
If you increase the optimizing level (at least in gcc), the behaviour you see would change.
When you call bar() from main(), it sets a = 42 which lives on the stack one int down from where main() executes. When you call foo() from main() it prints the value of a which in this scope is also on the stack one int down from where main() executes.
By calling bar() first, you have set data on the stack, and since foo() and bar() have the same call frame, bar()'s a and foo()'s a end up in the same memory address.
As other answers have noted, though, this is undefined behavior. In this case, the value persists on the stack and ends up in the same location.
Related
Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 1 year ago.
Improve this question
It has been on my mind for a while now.
How is space managed when we use a function.
Particularly this:
main()
{
printf("Helloworld");
}
and this:
void fun()
{
printf("Helloworld");
}
main()
{
fun();
}
So in terms of memory consumption are both of these the same? Or one of them is consuming lesser memory.
I understand that in a large program functions help us not repeating the same codes again and again AND also it releases its space every time it ends, But I want to know what happens in a small program where memory consumption is insignificantly small where the memory release of function after it ends has no significant effect.
What are the pro's and con's of function in this case
The C standard doesn't tell anything about memory consumption when using a function. An implementation (i.e. a specific compiler on a specific computer system) is free to do function calls the way it wants. It's even allowed to suppress function calls and put the functions code directly where the call was (called: inline). So there is no answer that will cover all systems in all situations.
Most systems uses a stack for handling function calls. A stack is a pre-allocated memory block that is assigned to the program at start up. The running program keeps track of the memory used within that block using a stack pointer. When a function is called, the stack pointer is changed according to the memory requirement for the function. When the function returns, the stack pointer is changed back to the original value. This allows for fast allocation and deallocation of variables local to the function and also any overhead memory used for the call itself (e.g. for storing a return address, cpu registers, etc.).
Since the stack is a pre-allocated fixed memory block, there is really no extra memory consumption involved in a function call. It's only a matter of using the already allocated memory.
However, if you do many nested function calls, you may run out of stack memory but that's another issue.
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 5 years ago.
Improve this question
#include<stdio.h>
int main() {
int j=65;
printf("j>=65?%d:%c\n",j);
return 0;
}
Ok it is understood that in place of %d ,value of j will be printed but why %c is replaced by ö ,i am unable to understand the output of this program , explain the printf statement.
You put doublequotes in a wrong place: you quoted the entire expression, rather than making your format string a conditional:
printf((j >= 65 ? "%d\n" : "%c\n"), j);
Your j >= 65 ? ... : ... expression is part of the string literal. C compiler does not "see" it as anything related to j. Hence the format string contains two format specifiers, with a single printed item; that's undefined behavior.
UB manifests itself in different ways; on your particular system a junk character 'ö' gets printed. This, however, is not a guaranteed behavior - on other systems you may get a different output, or a crash. See this Q&A for an explanation of UB.
This is enough I suppose for explaining whatever you have shown. And the behavior you see can be anything given that it is undefined.
From standard
The fprintf function writes output to the stream pointed to by stream,
under control of the string pointed to by format that specifies how
subsequent arguments are converted for output. If there are
insufficient arguments for the format, the behavior is undefined.
Emphasis mine.
The short answer for this is that this is undefined behavior, the character that gets printed could be anything and the program may even crash.
The longer answer is that old compilers did not check printf strings against the arguments passed, and so by default compilers to not treat this as an error. If you enable the correct warnings (-Wformat) it will complain about this at compile time, and with -Werror the warning will be escalated to an error. Because this is not checked at compile time, as many arguments as are needed are fetched from where they should be on the call stack. This means that first argument after the last specified argument probably has to do with the return address for the stack frame or something, but after that you start to push into unallocated memory. Either way, the behavior is undefined.
If you're interested in more details, this stack overflow answer explains it well.
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 5 years ago.
Improve this question
I am trying to inject executable code in memory using C. The executable should be able to read it's own code and copy it to some other location referenced by a pointer. The general template code is as follows
int
main(){
int (*main_ptr)();
main_ptr=main; // make the pointer point to start of main
/*
* rest of the code.
*
*/
/*Now I am trying to print the first 10 bytes of the main function.
* just to see if it is possible to access main's code.
*/
for(int i=0;i<10;i++)
printf("%x ",*main_ptr++);
return 0;
}
but the output is the value of the pointer (i.e. address of main function), not the value to which it points (the code of the main function). I had read somewhere that C does not dereference function pointers. But I do not know why. Is there a way to get around this?
Or, is there another way for a program to access its own code section?
P.S. I understand that many may think this is a stupid question and does not contribute significantly to research and all that. But I'am trying to understand how malware is written and given the absence of material on the web, it has been frustrating, so I decided to try this myself. Any help would be great.
There are 2 issue with your code (even though as such it is UB to be strict).
But even from any implementations point of view there are the following issues
None of the implementations define the * operator for function pointer.
None of the implementations define the ++ operator on the function pointers because size of a function is not defined.
But most implementations do define casting a fptr to void* and then to other data pointers even though it is UB.
You can make use of that fact.
I tried the simple modification of your code -
for(i=0;i<10;i++)
printf("%x ",*((int*)main_ptr++));
And it produced the "expected" behavior with gcc (MinGW64), compared the output against objdump.
Finally this goes with the warning that none of the approaches are portable. Perhaps there is no portable way to achieve what you are doing.
If you just have to get the same code as main, one way could be to read the actual binary (pointed by arg[0]). Parse the headers to find main and then read the bytes from there. Since reading the file would give you a data pointer there is no UB there.
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 5 years ago.
Improve this question
I made this small code in C:
#include <stdio.h>
int alo();
int main()
{
printf ("%d",alo());
}
int alo(int i, int x)
{
return (x);
}
but it seems when I run it without giving any argument to alo it prints a completely random number.
I just want to know, since I suppose it can't be 100% random, what number is this in reality and where does it come from, and also if I can predict it. Note that this is pure curiosity.
I guess it has something to deal with memory reading, but how this particular bug exactly functions?
Your alo function accepts (i.e. requires!) two parameters, but you called it without any arguments. The behavior is undefined in this case.
You declared your function (before main) without a prototype. This means that it is your responsibility to supply the correct number of arguments of correct type in all calls to alo. The compiler will not help you to verify the correctness of such calls.
For this reason a good idea is to1 always declare your functions with prototypes
int alo(int i, int x);
so that the compiler will help you to ensure that you are calling your function properly.
In practice the implementation of alo blindly follows its parameter passing convention and reads the storage location that is supposed to contain the value of parameter x. The resultant value is retuned from alo.
What kind of storage location is used for passing x depends on the implementation details. It could be a memory area or a CPU register. Whatever residual/garbage value was residing in that storage location before the call is returned from alo.
OK, Google for:
you own hardware architecture, (CPU, registers, memory etc),
assembler,
machine code,
instruction set,
debugger,
stack,
calling convention,
parameters,
arguments
When you understand the above, you are equipped to investigate the UB on the computer that it manifests on. Next box, next architecture, next week, it may behave differently:(
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 6 years ago.
Improve this question
I am using the below mentioned to simply learn about malloc. As I have heard and studied that malloc allocate an unintialized storage for you. So the output of this program should be a garbage value. But I am getting 0 as the output. Please tell me what is wrong here?
#include <stdio.h>
#include <stdlib.h>
int main(void) {
int *x =(int*)malloc(100000000*sizeof(int));
printf("%d",x[0]);
return 0;
}
OUTPUT 0
If malloc returns a null-pointer, and you dereference this null-pointer, you have undefined behavior.
If it doesn't return NULL, then the contents of the memory is indeterminate and using it in any way without initialization is still undefined behavior.
But to explain your behavior, if you get a non-null pointer back, then one of the possible value of the indeterminate values is zero. If you get a null-pointer back, then you might a well might had a crash instead of printing a zero.
Also, some environments might initialize memory to certain values when debugging. Clearing everything (i.e. setting most or everything to zero) is common when running in a debugger
That's the problem with garbage (as well as with undefined behavior) — it could be anything. And among the behaviors that fall under the category of "anything" is looking like it's doing something sensible.
(P.S. you should also test the return value of malloc; errors can happen, and it will signify the error by returning a null pointer)
You are printing the contents of storage with an indeterminate value. This is undefined behaviour. Anything can happen. Some of the things that can happen is the application crashing, your washing machine starting to wash, or your computer printing the number zero.