473,763 Members | 1,908 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

standard way to determine depth in stack

I can't see to easily find this on google or in a newsgroup

Is there a standard function/macro/whatever you can call and determine
the distance in a C program how deep one is in the C call stack from
main.

Something along the lines:

int main()
{
int i = stackdepth();
f2()
}

here i == 0.

void f2()
{
int i = stackdepth();
}

here i == 1

and so on.

I'm interested in nonstandard ways (if a standard way does not
suffice), or any crazy ideas.

Feb 21 '07 #1
13 3841
so**********@gm ail.com wrote:
I can't see to easily find this on google or in a newsgroup

Is there a standard function/macro/whatever you can call and determine
the distance in a C program how deep one is in the C call stack from
main.
No - as some people here enjoy pointing out, there might not be a stack!
>
I'm interested in nonstandard ways (if a standard way does not
suffice), or any crazy ideas.
For those, you should ask on a forum for your compiler and or OS.

--
Ian Collins.
Feb 21 '07 #2
softwaredoug writes:
Is there a standard function/macro/whatever you can call and
determine the distance in a C program how deep one is in the C
call stack from main.
There is no standard way. It depends on your operating system and
possibly your compiler. Ask in a group for programming in your OS.

--
Regards,
Hallvard
Feb 21 '07 #3
so**********@gm ail.com a écrit :
I can't see to easily find this on google or in a newsgroup

Is there a standard function/macro/whatever you can call and determine
the distance in a C program how deep one is in the C call stack from
main.

Something along the lines:

int main()
{
int i = stackdepth();
f2()
}

here i == 0.

void f2()
{
int i = stackdepth();
}

here i == 1

and so on.

I'm interested in nonstandard ways (if a standard way does not
suffice), or any crazy ideas.
You can do it as follows:
1) In the main function, get the address of the first local variable:

void *stacktop;

int main(void)
{
int dummy;

stacktop = (void *)&dummy;
......

}
2)
Now, you can write

long long stackdepth(void )
{
int dummy;
long long top = (long long)stacktop;
long long bottom = (long long)&dummy;

long long result = top - bottom;
if (result < 0)
result = -result;
return result;
}

3)
Please ignore all stupid remarks like "this is not portable".
This is obviously not portable to any machine. It requires a
stack, and it supposes that an address fits in a long long.

4) Please ignore all stupid remarks like " this is undefined behavior
since you can't take the difference of two pointers that do not point to
the same object"

Have fun

jacob
Feb 21 '07 #4
jacob navia wrote:
so**********@gm ail.com a écrit :
>>
Is there a standard function/macro/whatever you can call and determine
the distance in a C program how deep one is in the C call stack from
main.

You can do it as follows:
1) In the main function, get the address of the first local variable:

void *stacktop;

int main(void)
{
int dummy;

stacktop = (void *)&dummy;
......

}
2)
Now, you can write

long long stackdepth(void )
{
int dummy;
long long top = (long long)stacktop;
long long bottom = (long long)&dummy;

long long result = top - bottom;
if (result < 0)
result = -result;
return result;
}
0) this doesn't answer the OP's question, which was how many calls away
from main the current function is.

--
Ian Collins.
Feb 21 '07 #5
Ian Collins a écrit :
0) this doesn't answer the OP's question, which was how many calls away
from main the current function is.
The OP wrote "how deep one is in the C call stack". Yes, it could be
interpreted as you say, or literally, i.e. how deep is the stack.

To the original poster (OP): to know the number of procedures
stacked you have no other way than to read the debug information...
Not very easy...
Feb 21 '07 #6
jacob navia wrote:
Ian Collins a écrit :
>0) this doesn't answer the OP's question, which was how many calls away
from main the current function is.

The OP wrote "how deep one is in the C call stack". Yes, it could be
interpreted as you say, or literally, i.e. how deep is the stack.
To quote his example:

Something along the lines:

int main()
{
int i = stackdepth();
f2()
}

here i == 0.

void f2()
{
int i = stackdepth();
}

here i == 1

Pretty unambiguous.

--
Ian Collins.
Feb 22 '07 #7
Ian Collins <ia******@hotma il.comwrites:
so**********@gm ail.com wrote:
>I can't see to easily find this on google or in a newsgroup

Is there a standard function/macro/whatever you can call and determine
the distance in a C program how deep one is in the C call stack from
main.
No - as some people here enjoy pointing out, there might not be a stack!
[...]

That's true, but the problem is well-defined (or at least can be
well-defined) given a decent definition for "call stack". It's a
sensible question, but the answer is "No, the language defines no way
to do that".

The closest you can come in portable code is to add an extra "depth"
parameter to every function in your program, and in every function
call pass the current value plus one. For example:

#include <stdio.h>

void foo(int data, char *stuff, int depth)
{
printf("In foo, depth is %d\n", depth);
}

void bar(double stuff, char *oreo, int depth)
{
printf("In bar, depth is %d\n", depth);
foo(42, oreo, depth + 1);
printf("Back in bar, depth is %d\n", depth);
}

int main(void)
{
bar(42.0, "blah", 1);
return 0;
}

But this is probably more effort than it's worth.

You may be able to obtain this information in a debugger, but that
doesn't give your program access to it.

--
Keith Thompson (The_Other_Keit h) ks***@mib.org <http://www.ghoti.net/~kst>
San Diego Supercomputer Center <* <http://users.sdsc.edu/~kst>
We must do something. This is something. Therefore, we must do this.
Feb 22 '07 #8
On Feb 21, 3:21 pm, jacob navia <j...@jacob.rem comp.frwrote:
Ian Collins a écrit :
0) this doesn't answer the OP's question, which was how many calls away
from main the current function is.

The OP wrote "how deep one is in the C call stack". Yes, it could be
interpreted as you say, or literally, i.e. how deep is the stack.
It's best to read an entire message before responding. The phrase you
quoted could be misinterpreted as you did, but the entire message
couldn't.

Feb 22 '07 #9
jacob navia <ja***@jacob.re mcomp.frwrites:
so**********@gm ail.com a écrit :
>I can't see to easily find this on google or in a newsgroup
Is there a standard function/macro/whatever you can call and
determine the distance in a C program how deep one is in the C call
stack from main.
[...]
You can do it as follows:
1) In the main function, get the address of the first local variable:

void *stacktop;

int main(void)
{
int dummy;

stacktop = (void *)&dummy;
.....

}
2)
Now, you can write

long long stackdepth(void )
{
int dummy;
long long top = (long long)stacktop;
long long bottom = (long long)&dummy;

long long result = top - bottom;
if (result < 0)
result = -result;
return result;
}

3)
Please ignore all stupid remarks like "this is not portable".
This is obviously not portable to any machine. It requires a
stack, and it supposes that an address fits in a long long.

4) Please ignore all stupid remarks like " this is undefined behavior
since you can't take the difference of two pointers that do not point to
the same object"
jacob is giving you bad advice. The code assumes far more than the
existence of a stack and that an address fits in a long long. (Note
that not all pointer types are necessarily the same size, though they
commonly are.)

It assumes that the type "long long" exists; it's required in C99, but
not in C90, and some compilers will reject it in strict C90 mode.

As long as he's assuming C99, he might as well use intptr_t or
uintptr_t from <stdint.h>, which is guaranteed to be able to hold a
pointer value. If no such type exists, then the types will not be
declared, causing any program that uses it to fail compilation rather
than quietly misbehave at run time.

Converting pointers to long long and subtracting the converted results
is a silly way to compute the difference between two pointer values.
I once corrected a bug in a large piece of software that was caused by
just that kind of operation. The code failed on one of the platforms
it was required to support, because pointer representations and
pointer-to-integer conversions on that platform, though their behavior
was perfectly conforming as far as the standard is concerned, did not
match the (unnecessary) assumptions made by the original author. The
platform in question (Cray T90) is not one you're likely to run into,
but "there are more things in Heaven and Earth, Horatio ...".

You can subtract two pointers, yielding an integer result
(specifically, a result of type ptrdiff_t). If the two pointers don't
point into the same object, the subtraction invokes undefined
behavior. If you're willing to live with that, and assume that the
subtraction will behave sanely, then subtracting the pointers directly
is better than converting to integers first; the latter avoids the
undefined behavior, but can silently misbehave in some cases.

The "stupid remarks" that jacob correctly anticipated are not stupid
at all. Rather, they are legitimate warnings from people who actually
know the C language. The code he posted really isn't portable, and
comparing or subtracting pointers that don't point into the same
object really does invoke undefined behavior. You need to be aware of
these facts. Once you're aware of them, you can, if you wish, write
non-portable code that depends on assumptions beyond the requirements
of the C standard; sometimes code that works only on a limited set of
platforms is good enough.

Finally, of course, jacob's proposed solution doesn't answer your
question at all. If it works as intended (which it might on many
systems), it gives you the depth in bytes, not the number of function
calls.

--
Keith Thompson (The_Other_Keit h) ks***@mib.org <http://www.ghoti.net/~kst>
San Diego Supercomputer Center <* <http://users.sdsc.edu/~kst>
We must do something. This is something. Therefore, we must do this.
Feb 22 '07 #10

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

48
2732
by: Michael Sig Birkmose | last post by:
Hi everyone! Does anyone know, if it is possible to meassure the maximum stack usage of a C program throughout it's entire execution? -- Michael Birkmose
20
3502
by: Sushil | last post by:
Hi gurus I was reading FAQ "alloca cannot be written portably, and is difficult to implement on machines without a conventional stack." I understand that the standard does not mandate "heap" or "stack" I'm curious to know the implemenations which dont have stack or heap.
13
25558
by: Ben R. Bolton | last post by:
The documentation indicates that the threads "default stack size" is 1MB. The work "default" implies that it can be changed. Is it possible to change the StackSize in .NET? If so how? Is it possible to determine the amount of memory used in the current stack? Any assistance would be appreciated. Ben
2
1755
by: Raider | last post by:
Operator new() must throw std::bad_alloc in no more dynamical memory left, but what standard says about stack? Is there a some way to handle stack overflow? Raider
6
2646
by: Daz | last post by:
Hi everyone! It is indeed, once again time for me to ask another stupid question. I have been searching around on the net for quite a while, and can't find anything that explains 'exactly' what a stack overflow is, or how it's detected. I know that it's leterally putting too many objects on the stack, but how many objects can you have on the stack, or do OSs only allow a certain number of recursive calls to functions?
7
2082
by: David T. Ashley | last post by:
Is there any portable method for identifying the caller of a function, its caller, and so on, at runtime, without using a debugger? Clearly, one can dissect the stack frame and trace it back. But this method isn't very portable (it requires a knowledge of the machine). Is there any method supported by the language or by standards? (Maybe, similar to the way variable-length argument lists are handled?)
22
2299
by: Chris Thomasson | last post by:
I am thinking about using this technique for all the "local" memory pools in a paticular multi-threaded allocator algorithm I invented. Some more info on that can be found here: http://groups.google.com/group/comp.arch/browse_frm/thread/24c40d42a04ee855 Anyway, here is the code snippet: #include <cstdio> #include <cstddef>
4
6355
by: =?Utf-8?B?cmFuZHkxMjAw?= | last post by:
Visual Studio 2005, C# WinForms application: Here’s the question: How can I increase the standard 1 MB stack size of the UI thread in a C# WinForms application? Here’s why I ask: I’ve inherited some code that at the view (User Interface) layer kicks off a background worker thread. At the service layer (think CAB service layer), there’s quite a lot of the following:
87
5562
by: CJ | last post by:
Hello: We know that C programs are often vulnerable to buffer overflows which overwrite the stack. But my question is: Why does C insist on storing local variables on the stack in the first place? I can see two definite disadvantages with this: 1) deeply nested recursive calls to a function (especially if it defines
0
9389
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10149
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
10003
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
0
8825
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
7370
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
6643
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5271
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
5410
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
3
2797
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.