问题
Write a portable function in C (with no assembly) that returns the size of its stack frame
int stackframe_size()
{
}
Attempted solving it as below - This function returns 228 bytes when compiled with VS 2010. Is there a way to verify its correctness?
int stackframe_size(int run)
{
int i ;
if(!run)
{
return ((int)(&i) - stackframe_size(++run));
}
return (int)(&i);
}
Invoked as:
int main()
{
printf("\nSize of stackframe_size() is: %d bytes",stackframe_size(0)) ;
return 0;
}
回答1:
No such portable function is possible.
Your attempt is probably about as close as you can get, but the pointer subtraction has undefined behavior. More generally, p1 - p0
, where p0
and p1
are pointers to distinct objects, has undefined behavior.
Except that your code subtracts to int
values that are the result of conversions from addresses. Direct subtraction of the pointers is more likely to work -- and the pointers should be of type char*
or unsigned char*
. There are many implementations where int
is too small to hold a converted pointer, and some where pointers have a more complicated representation than you assume, and converting them to even a sufficiently large integer type will not necessarily give you a meaningful result.
There are real-world C implementations that don't use a "stack" in the sense of a contiguous region of memory on which "stack frames" are pushed and popped. (There has to be a "stack" in the sense of a first-in last-out data structure, but the way that "stack" is implemented is entirely unspecified.) Some IBM mainframe implementations, for example, allocate memory for a function call via something like a heap, so that there is no defined relationship between the addresses of the local variables for two such calls.
You can probably write a function in pure C (without assembly language) that gives you the size of a stack frame for a particular implementation. But since the C language itself has no concept of a "stack frame" (the standard doesn't even use the word "stack"), it cannot be done portably.
回答2:
I wanted to check if there is a clever/cleaner way to do this without adding local variables
You could use &run
instead of &i
- that would save you a local variable.
Is there a way to verify its correctness?
Use a debugger! Check the stack pointer register at the spots you care about, watch the spills take place, etc.
来源:https://stackoverflow.com/questions/28358213/portable-function-in-c-with-no-assembly-that-returns-the-size-of-its-stack-fra