473,811 Members | 3,627 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

[C#] Fatal stack overflow

I have a recursive function that I would like to do a lot of recursive
calls (preferebly 2^20 in total)

The function is called as (with maxi = e.g. 100000)

DoRecursion(0,m axi,bseed,sha);

And the total code is

static void Main(string[] args)
{
long maxi = Convert.ToInt64 (args[0]);
try
{
SHA1 sha = new SHA1CryptoServi ceProvider();
// initial seed
string seed = System.Guid.New Guid().ToString ();
byte[] bseed = (new UTF8Encoding()) .GetBytes(seed) ;

System.DateTime time1 = DateTime.Now;
DoRecursion(0,m axi,bseed,sha);
System.DateTime time2 = DateTime.Now;

// interval is created
System.TimeSpan interval = time2 - time1;
Console.WriteLi ne("Millisecond s: \t {0}",interval.T otalMillisecond s.ToString());
}
catch (Exception e)
{
Console.WriteLi ne("Error: {0}",e.Message) ;
}
}

private static void DoRecursion(lon g i, long maxi, byte[] seed, SHA1 sha1)
{
try
{
byte[] result;
result = sha1.ComputeHas h(seed);
if (i < maxi)
{
i++;
DoRecursion(i,m axi,result,sha1 );
}
}
catch (Exception e)
{
Console.WriteLi ne(e.Message);
}
}

But every time I reach a value 15196 for i, I get the error "Fatal stack
overflow error."

What am I doing wrong?

--
Jesper Stocholm
http://stocholm.dk
Give a man a fish and he will have food for a day,
give a man an elephant, and he will have food for a week.
Nov 15 '05 #1
4 3855
Nesting function calls a million levels deep is hardly ever a good idea, and
I don't see anything in this function that would require recursion. It looks
like you're applying SHA1 to an array of bytes over and over again and not
doing anything with the result except for timing it. You should be able to
replace your recursive function with a simple loop.

If you really do need to use recursion for some reason that's not
illustrated here, you can cut down on the number of parameters you put on
the stack for each call. Based on what the function actually does, you could
make them all member variables and not pass any of them on the stack.

"Jesper Stocholm" <j@stocholm.inv alid> wrote in message
news:Xn******** *************** @192.38.208.86. ..
I have a recursive function that I would like to do a lot of recursive
calls (preferebly 2^20 in total)

The function is called as (with maxi = e.g. 100000)

DoRecursion(0,m axi,bseed,sha);

And the total code is

static void Main(string[] args)
{
long maxi = Convert.ToInt64 (args[0]);
try
{
SHA1 sha = new SHA1CryptoServi ceProvider();
// initial seed
string seed = System.Guid.New Guid().ToString ();
byte[] bseed = (new UTF8Encoding()) .GetBytes(seed) ;

System.DateTime time1 = DateTime.Now;
DoRecursion(0,m axi,bseed,sha);
System.DateTime time2 = DateTime.Now;

// interval is created
System.TimeSpan interval = time2 - time1;
Console.WriteLi ne("Millisecond s: \t {0}",interval.T otalMillisecond s.ToString()); }
catch (Exception e)
{
Console.WriteLi ne("Error: {0}",e.Message) ;
}
}

private static void DoRecursion(lon g i, long maxi, byte[] seed, SHA1 sha1)
{
try
{
byte[] result;
result = sha1.ComputeHas h(seed);
if (i < maxi)
{
i++;
DoRecursion(i,m axi,result,sha1 );
}
}
catch (Exception e)
{
Console.WriteLi ne(e.Message);
}
}

But every time I reach a value 15196 for i, I get the error "Fatal stack
overflow error."

What am I doing wrong?

--
Jesper Stocholm
http://stocholm.dk
Give a man a fish and he will have food for a day,
give a man an elephant, and he will have food for a week.

Nov 15 '05 #2
A case for C# tailcalls? ;)

The managed stack is only 1MB by default (AFAIK). So, if you do enough
recursion to allocate more than that, you'll get this exception. I'd
suggest moving the recursion to inside one method.

-mike
MVP

"Jesper Stocholm" <j@stocholm.inv alid> wrote in message
news:Xn******** *************** @192.38.208.86. ..
I have a recursive function that I would like to do a lot of recursive
calls (preferebly 2^20 in total)

The function is called as (with maxi = e.g. 100000)

DoRecursion(0,m axi,bseed,sha);

And the total code is

static void Main(string[] args)
{
long maxi = Convert.ToInt64 (args[0]);
try
{
SHA1 sha = new SHA1CryptoServi ceProvider();
// initial seed
string seed = System.Guid.New Guid().ToString ();
byte[] bseed = (new UTF8Encoding()) .GetBytes(seed) ;

System.DateTime time1 = DateTime.Now;
DoRecursion(0,m axi,bseed,sha);
System.DateTime time2 = DateTime.Now;

// interval is created
System.TimeSpan interval = time2 - time1;
Console.WriteLi ne("Millisecond s: \t {0}",interval.T otalMillisecond s.ToString()); }
catch (Exception e)
{
Console.WriteLi ne("Error: {0}",e.Message) ;
}
}

private static void DoRecursion(lon g i, long maxi, byte[] seed, SHA1 sha1)
{
try
{
byte[] result;
result = sha1.ComputeHas h(seed);
if (i < maxi)
{
i++;
DoRecursion(i,m axi,result,sha1 );
}
}
catch (Exception e)
{
Console.WriteLi ne(e.Message);
}
}

But every time I reach a value 15196 for i, I get the error "Fatal stack
overflow error."

What am I doing wrong?

--
Jesper Stocholm
http://stocholm.dk
Give a man a fish and he will have food for a day,
give a man an elephant, and he will have food for a week.

Nov 15 '05 #3
If you can't re-write the method as Bret suggested, you can take the easy
way out and just significantly up the stock size (if you have the editbin
tool available):
http://blogs.geekdojo.net/richard/posts/207.aspx

--
Veuillez m'excuser, mon Français est très pauvre. Cependant, si vous voyez
mauvais C #, c'est mon défaut!
"Jesper Stocholm" <j@stocholm.inv alid> wrote in message
news:Xn******** *************** @192.38.208.86. ..
I have a recursive function that I would like to do a lot of recursive
calls (preferebly 2^20 in total)

The function is called as (with maxi = e.g. 100000)

DoRecursion(0,m axi,bseed,sha);

And the total code is

static void Main(string[] args)
{
long maxi = Convert.ToInt64 (args[0]);
try
{
SHA1 sha = new SHA1CryptoServi ceProvider();
// initial seed
string seed = System.Guid.New Guid().ToString ();
byte[] bseed = (new UTF8Encoding()) .GetBytes(seed) ;

System.DateTime time1 = DateTime.Now;
DoRecursion(0,m axi,bseed,sha);
System.DateTime time2 = DateTime.Now;

// interval is created
System.TimeSpan interval = time2 - time1;
Console.WriteLi ne("Millisecond s: \t {0}",interval.T otalMillisecond s.ToString()); }
catch (Exception e)
{
Console.WriteLi ne("Error: {0}",e.Message) ;
}
}

private static void DoRecursion(lon g i, long maxi, byte[] seed, SHA1 sha1)
{
try
{
byte[] result;
result = sha1.ComputeHas h(seed);
if (i < maxi)
{
i++;
DoRecursion(i,m axi,result,sha1 );
}
}
catch (Exception e)
{
Console.WriteLi ne(e.Message);
}
}

But every time I reach a value 15196 for i, I get the error "Fatal stack
overflow error."

What am I doing wrong?

--
Jesper Stocholm
http://stocholm.dk
Give a man a fish and he will have food for a day,
give a man an elephant, and he will have food for a week.

Nov 15 '05 #4
Bret Mulvey [MS] wrote :
Nesting function calls a million levels deep is hardly ever a good
idea, and I don't see anything in this function that would require
recursion. It looks like you're applying SHA1 to an array of bytes
over and over again and not doing anything with the result except for
timing it. You should be able to replace your recursive function with
a simple loop.
Yes - what I am doing is creating a chain of hash-values, so the output
of SHA1 is in the next recursion used as input to SHA1.
If you really do need to use recursion for some reason that's not
illustrated here, you can cut down on the number of parameters you put
on the stack for each call. Based on what the function actually does,
you could make them all member variables and not pass any of them on
the stack.


I re-wrote the recursive method to a FOR-loop instead that updates a
member variable. It now works like a charm.

Thanks, :)

--
Jesper Stocholm
http://stocholm.dk
Give a man a fish and he will have food for a day,
give a man an elephant, and he will have food for a week.
Nov 15 '05 #5

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

Similar topics

8
9999
by: Tim Tyler | last post by:
I'm getting fatal errors when executing code - and my error handler is failing to trap them - so I get no stack backtrace :-( The error I am getting is: "Fatal error: Call to a member function fetchRow() on a non-object." What are the available options here? Am I supposed to check I have a real object whenever I perform
7
7079
by: Aguilar, James | last post by:
Hello all, To begin, yes, this -is- a homework assignment. However, it is for my Algorithms class, and my instructor has given us explicit permission to use "expert" groups like newsgroups, so if that's your only reason not to help, please do. Otherwise, I guess it's OK. But, just remember, I'm not asking you to do my work for me, just to point out my error. My problem is not with the algorithm itself (standard divide and conquer on...
19
3146
by: Jim | last post by:
I have spent the past few weeks designing a database for my company. The problem is I have started running into what I believe are stack overflow problems. There are two tab controls on the form (nested), three list views, one tree control with up to 30,000 nodes, maybe 15 comboboxes (half of which have a large recordset as rowsource), 20 or so buttons and around 30 text boxes (not to mention the images, labels, etc and around 1000 lines...
4
9058
by: Victor | last post by:
Hello, I've got a situation in which the number of (valid) recursive calls I make will cause stack overflow. I can use getrlimit (and setrlimit) to test (and set) my current stack size. However, it is not as straightforward to determine the base address for my stack space. The approach I have taken is to save the address of an automatic variable in main( ), and assume this is a fairly good indicator of my base address. Then, I can...
0
1516
by: pillars | last post by:
I have been developing an application in Windows CE.Net using the .Net Compact Framework and C#. Data is saved to a local Sql Server CE database and then transferred wirelessly to a central server. The device has to open a connection every 5 minutes, transfer all records and then disconnect. I have been running tests to verify the capacity of the database, if, for example, the network goes down and transfers cannot be made. I have...
2
2896
by: David W. Walker | last post by:
I am attempting to port a C code that runs OK on a number of Linux and Unix machines to Windows XP using Visual Studio C++. I have set the program up as a console application, but when I try to run it I get a stack overflow: Unhandled exception at 0x0041e715 in NewMD.exe: 0xC00000FD: Stack overflow. The call stack is: NewMD.exe!_chkstk() Line 91 NewMD.exe!mainCRTStartup() Line 259 +0x19
351
13174
by: CBFalconer | last post by:
We often find hidden, and totally unnecessary, assumptions being made in code. The following leans heavily on one particular example, which happens to be in C. However similar things can (and do) occur in any language. These assumptions are generally made because of familiarity with the language. As a non-code example, consider the idea that the faulty code is written by blackguards bent on foulling the language. The term...
2
3742
by: Ali | last post by:
Hi, I got stack overflow errors while using an unmanaged dll from managed c# application. When i use editbin.exe to increase stack size of app , it works. Is there a way to increase stack size of app (or most probably Clr) so that app starts with a larger stack, like using the old /F switch in Visual Studio C++ 6.0.
7
22052
by: amit.atray | last post by:
Environement : Sun OS + gnu tools + sun studio (dbx etc) having some Old C-Code (ansi + KR Style) and code inspection shows some big size variable (auto) allocated (on stack) say for ex. char a; (this type of code and other complex mallc/free etc is used frequently and total approx 450 files, each file is of approx/avg 1000 line,
0
9730
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9605
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
10651
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
10392
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
9208
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...
0
6893
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
5555
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
5693
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
3
3020
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.