CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Page 1 of 2 12 LastLast
Results 1 to 15 of 16
  1. #1
    Join Date
    Feb 2011
    Posts
    5

    Stack Overflow Error?

    I am writing a program to act as a postage calculator. I am getting a stack overflow error and I can't for the life of me figure out WHY it is happening. Can one of you gents point me in the right direction??

    Code:
    namespace Lab2
    {
        public class Package
        {
            private string FName;
            private string LName;
            private string Address;
            private string City;
            private string State;
            private string ZipCode;
            private decimal Weight = 0.0M;// in ounces
            private decimal Cost = 0.00M;// per ounce
    
            // constructor
            public Package(string FirstName1, string LastName1, string Address1, string City1, string State1,
                string ZipCode1, decimal Weight1, decimal Cost1)
            {
                // implicit call to object constructor
                FName = FirstName1;
                LName = LastName1;
                Address = Address1;
                City = City1;
                State = State1;
                ZipCode = ZipCode1;
            }// end Package constructor
    
            // read-only property that gets first name
            public string FirstName1
            {
                get
                {
                    return FName;
                }// end get
            }// end property FirstName1
    
            // read-only property that gets last name
            public string LastName1
            {
                get
                {
                    return LName;
                }// end get
            }// end property LastName1
    
            // read-only property that gets address
            public string Address1
            {
                get
                {
                    return Address;
                }// end get
            }// end property Address11
    
            // read-only property that gets city
            public string City1
            {
                get
                {
                    return City;
                }//end get
            }// end property City1
    
            // read-only property that gets state
            public string State1
            {
                get
                {
                    return State1;
                }//end get
            }// end property State1
    
            // read-only property that gets zip
            public string ZipCode1
            {
                get
                {
                    return ZipCode;
                }// end get
            }// end property ZipCode1
    
            // read-only property that gets weight
            public decimal Weight1
            {
                get
                {
                    return Weight;
                }// end get
                set
                {
                    Weight = (value < 0) ? 0 : value;
                }// end set
            }// end property Weight1
    
            // read-only property that gets cost
            public decimal Cost1
            {
                get
                {
                    return Cost;
                }//end get Cost1
                set
                {
                    Cost = (value < 0) ? 0 : value;
                }// end set
            }// end property Cost1
    
            // Calculate cost
            public virtual decimal CalculateCost()
            {
                return Weight1 * Cost1;
            }// end method CalculateCost
    
            // return string representation of Package object
            public override string ToString()
            {
                return string.Format(
                    "{0}: {1} {2}: \n{3}: {4}\n{5}: {6} \n{7}: {8}\n{9}: {10}: \n{11}: {12} \n{13:F2}: {14} \n{15:C}: {16}",
                    "Sender's First Name", FirstName1, 
                    "Sender's LastName1", LastName1,
                    "Address", Address1,
                    "City", City1,
                    "State", State1, 
                    "ZipCode",ZipCode1,
                    "Weight", Weight1,
                    "Cost", Cost1);
            }// end ToString method
    
        }// end class Package
    }// end namespace Lab2
    
     
    
    namespace Lab2
    {
        public class TwoDayPackage : Package
        {
            private decimal Fee = 5.00M;// 2-day flat fee delivery charge
    
            //derived class constructor
            public TwoDayPackage(string FirstName1, string LastName1, string Address1, string City1,
                string State1, string ZipCode1, decimal Weight1, decimal Cost1)
                : base(FirstName1, LastName1, Address1, City1, State1, ZipCode1, Weight1, Cost1)
            {
                Fee1 = Cost1;
            }// end constructor
    
            // property that gets and sets
            public decimal Fee1
            {
                get
                {
                    return Fee;
                }// end get
                set
                {
                    Fee = (value < 0) ? 0 : value;
                }// end set
            }// end property Fee1
    
            // calculate total cost
            public override decimal CalculateCost()
            {
                return Fee1 + base.CalculateCost();
            }// end method CalculateCost
    
            // return string representation of TwoDayPackage
            public override string ToString()
            {
                return string.Format("Fee {0}\nFee: {1:C}",
                    base.ToString(), Fee1);
            }// end method ToString
        }// end class TwoDayPackage
    }// end namespace Lab2
    
     
    
    namespace Lab2
    {
        public class OverNightPackage : Package
        {
            private decimal AddFee = 10.00M;// additional fee per ounce for overnight delivery
    
            // derived class constructor
            public OverNightPackage(string FirstName1, string LastName1, string Address1, string City1, string State1,
                string ZipCode1, decimal Weight1, decimal Cost1)
                : base(FirstName1, LastName1, Address1, City1, State1, ZipCode1, Weight1, Cost1)
            {
                AddFee1 = Cost1;
            }// end constructor
    
            // property for AddFee1
            public decimal AddFee1
            {
                get
                {
                    return AddFee;
                }// end get
                set
                {
                    AddFee = (value < 0) ? 0 : value;
                }// end set
            }// end property AddFee1
    
            // calculate cost
            public override decimal CalculateCost()
            {
                return AddFee1 + base.CalculateCost();
            }// end method CalculateCost
    
            // return string representation of OverNightPackage
            public override string ToString()
            {
                return string.Format("Cost {0}\nAdditional Fee: {1:C}",
                    base.ToString(), AddFee1);
            }// end method ToString
        }// end class OverNightPackage
    }// end namespace Lab2
    
     
    
    namespace Lab2
    {
        public class PackageTest
        {
            public static void Main(string[] args)
            {
                // instantiate Package object
                Package Sender = new Package("Jane", "Doe", "121 Broad St", "Houston", "Texas", "77077",
                    5.0M, 10.00M);
                Sender.CalculateCost();
                Console.WriteLine(Sender.ToString());
    
                // instantiate TwoDayPackage object
                TwoDayPackage TwoDayPkg = new TwoDayPackage("John", "Doe", "1201 Main St",
                    "Dallas", "Texas", "75208", 7.5M, 13.00M);
    
                // instantiate OverNightPackage object
                OverNightPackage OverNightPkg = new OverNightPackage("Mary", "Bloom", "540 River Lane",
                    "Dallas", "Texas", "75055", 3.0M, 7.50M);
    
                // display Sender data
                Console.WriteLine("First name is: {0}", Sender.FirstName1);
                Console.WriteLine("Last name is: {0}", Sender.LastName1);
                Console.WriteLine("Address is: {0}", Sender.Address1);
                Console.WriteLine("City: {0}", Sender.City1);
                Console.WriteLine("State: {0}", Sender.State1);
                Console.WriteLine("Zip: {0}", Sender.ZipCode1);
                Console.WriteLine("Weight of package: {0:F2}", Sender.Weight1);
                Console.WriteLine("Cost of package: {0:C}", Sender.Cost1);
               
                Console.WriteLine(TwoDayPkg.ToString());
                Console.WriteLine(OverNightPkg.ToString());
                
            }
        }
    }

  2. #2
    Join Date
    Jun 2008
    Posts
    2,477

    Re: Stack Overflow Error?

    This is why. Look closely at what you are returning.

    Code:
    public string State1
    {
        get
        {
            return State1;
        }//end get
    }
    That is an example of infinite recursion.

    This is one argument against naming private instance members as you do. in C#, private member variables usually begin with an underscore and are followed by a lowercase letter (same with local variables.) So, "State" becomes _state. This is of course not a hard rule, but it is idiomatic and generally accepted as the style to use by the C# community.

    Also, you have a lot of comments that are absolutely useless. I know that almost all teachers require comments like that, so if this is a school project I understand, but n the real world comments like that just clutter up the code and add no value. Comments are supposed to explain *why* the code does what it does, not *what* the code does. Any programmer can tell what the code is doing by simply reading it, no comments required.
    Last edited by BigEd781; February 5th, 2011 at 08:26 PM.

  3. #3
    Join Date
    Feb 2011
    Location
    United States
    Posts
    1,016

    Re: Stack Overflow Error?

    StackOverflowExceptions occur when you have tried to call too many methods deep into the callstack. This is usually a sign of recursion without a base case or two methods which circularly call each other. In this case, the problem can be solved by modifying the Getter for State1 in the Package class. It currently reads:

    Code:
            public string State1
            {
                get
                {
                    return State1;
                }//end get
            }// end property State1
    When you order it to return State1, it calls the State1 getter again, which in turn calls the State1 getter... until you run out of stack space.

    It is easily corrected by replacing it with:

    Code:
            public string State1
            {
                get
                {
                    return State;
                }//end get
            }// end property State1
    Which will return the member variable State of package rather than calling the getter again.

    This sort of problem can be avoided by using some common conventions. Often, I use lowercase letter to name the member variables of my classes and Uppercase letters to name their getters/setters. Another common convention is to preceed member variables in the class with an underscore (_) to remember that they are member variables and not exposed.

    Note that solving that problem exposes another, but I will let you play with the debugging on that. What debugger/IDE are you using? Visual Studio is an excellent choice. There are some others that are good too. My favorite free, open-source one is SharpDevelop which you can get here: http://www.icsharpcode.net/opensource/sd/. A good IDE with a good debugger is a programmer's best friend. I understand though why you might be confused if this was your first encounter with StackOverflowExceptions.

    As a general note too, unless your instructor explicitly requires you to comment all curly brace closures ( } ), I would omit them. They merely clutter the code which hinders readability without actually convening that much information.

    I hope that helps!
    Best Regards,

    BioPhysEngr
    http://blog.biophysengr.net
    --
    All advice is offered in good faith only. You are ultimately responsible for effects of your programs and the integrity of the machines they run on.

  4. #4
    Join Date
    Jun 2008
    Posts
    2,477

    Re: Stack Overflow Error?

    Quote Originally Posted by BioPhysEngr View Post
    StackOverflowExceptions occur when you have tried to call too many methods deep into the callstack.
    We posted the same exact response

    To be a bit pedantic though, a stack overflow does not occur when you call too many methods, it occurs when you exceed the amount of memory allocated to the stack space of the current thread. Of course, infinite recursion is a way to cause that, but there are other ways as well.

  5. #5
    Join Date
    Feb 2011
    Location
    United States
    Posts
    1,016

    Re: Stack Overflow Error?

    Yes, good point. I don't think I can remember the last time I caused it by any other method in C# though. Thanks for the clarification; it is well worth remembering.
    Best Regards,

    BioPhysEngr
    http://blog.biophysengr.net
    --
    All advice is offered in good faith only. You are ultimately responsible for effects of your programs and the integrity of the machines they run on.

  6. #6
    Join Date
    Jun 2008
    Posts
    2,477

    Re: Stack Overflow Error?

    Yeah, it's pretty rare to be anything other than this in C# due to most objects being allocated on the heap. It would take a struct with a lot of stack allocated fields/member variables to overrun the stack space.

  7. #7
    Join Date
    Feb 2011
    Posts
    5

    Re: Stack Overflow Error?

    Guys,
    Thanks a bundle! You'll have to excuse my newbieness, I only had 1 semester in C++ prior to this, but luckily this is my last programming class I need for my EE degree. Everyone said the transition from C++ to C# would be easy, but to be honest I REALLY don't get it(I wanted to do java). I commented the living crap out of my code so that I could keep MYSELF in line, and the instructor has no issues with it.

    Again, I'll try some of the changes you guys mentioned and report back, thanks guys!

  8. #8
    Join Date
    Feb 2011
    Posts
    5

    Re: Stack Overflow Error?

    ***Update***

    I'm back to square one it seems.. I changed it to return State instead of State1, and the program compiles.

    I'm in VS2008 and everything works until I run the program..then I get the following command prompt error.


    "
    Unhandled Exception: System.FormatException: Index (zero based) must be greater
    than or equal to zero and less than the size of the argument list.
    at System.Text.StringBuilder.AppendFormat(IFormatProvider provider, String fo
    rmat, Object[] args)
    at System.String.Format(IFormatProvider provider, String format, Object[] arg
    s)
    at System.String.Format(String format, Object[] args)
    at Lab2.Package.ToString() in C:\Documents and Settings\toast\My Documents\Vi
    sual Studio 2008\Projects\Package Program\Package Program\Program.cs:line 120
    at Lab2.PackageTest.Main(String[] args) in C:\Documents and Settings\toast\My
    Documents\Visual Studio 2008\Projects\Package Program\Package Program\Program.c
    s:line 235
    Press any key to continue . . .
    "

    Arrrggghhh =/ Lemme keep looking some stuff up but can someone let me know as to whats still going wrong here =[

  9. #9
    Join Date
    Oct 2005
    Location
    Seattle, WA U.S.A.
    Posts
    353

    Re: Stack Overflow Error?

    Truncating the format string (or providing the additional operands) may help ...

    Code:
    "{0}: {1} {2}: \n{3}: {4}\n{5}: {6} \n{7}: {8}\n{9}: {10}: \n{11}: {12} \n{13:F2}: {14} \n{15:C}: {16}",
    I lopped off everything after {8}\n and it ran to completion .... did you forget to add the operands to support the format ?

    Another thought ... just noticed that you might wanna add a "\n" here and there ... I don't think the display is quite what you had in mind.

    If you run the debugger in the 'start debugging' mode with no breaks set, the debugger comes to a halt at the offending statement. MS really has equipped VS with a world-class debugger (IMHO) (an' the Exception printout is also very informative - what a great IDE !).
    Last edited by ThermoSight; February 6th, 2011 at 12:53 PM.

  10. #10
    Arjay's Avatar
    Arjay is offline Moderator / EX MS MVP Power Poster
    Join Date
    Aug 2004
    Posts
    13,490

    Re: Stack Overflow Error?

    Once you understand what is causing the stack overflow issue is to figure out how to prevent the problem from never happening again.

    One way to do this is to adopt a consistent property/field naming convention.

    One popular C# naming convention is to name Properties as Pascal case and Fields as camel case with a leading underscore.
    Code:
    public string State { get { return _state; } }
    private string _state;
    In this style, all local variables/ctor or method parameters get named as camel case (without the leading underscore)

    This avoids having to use 'this.' to disambiguate params from class fields.
    Code:
    public Package( string state )
    {
      _state = state; // no problem
    }
    vs (when leading underscore isn't used to denote class fields)
    Code:
    public Package( string state )
    {
      this.state = state;  // this works, but it's ugly to some folks
    }
    Another way to avoid issues is to use an auto property
    Code:
    public string State { get; set; }
    In fact, auto properties allow you to set access levels. For example, a public readonly property with a private setter would look like this:
    Code:
    public string State { get; private set; }
    Code:
    public Package( string state )
    {
      State = state;
    }
    I generally try to use autoproperties whenever possible because it reduces code clutter (imo).

  11. #11
    Join Date
    Jun 2008
    Posts
    2,477

    Re: Stack Overflow Error?

    Quote Originally Posted by jetter2 View Post
    Everyone said the transition from C++ to C# would be easy, but to be honest I REALLY don't get it(I wanted to do java).
    Yeah, they didn't know what they were talking about . The biggest similarity between C# and C++ is the syntax, pretty much everything else is different. You would have had the same issue going to java, which is similar in many ways to C# (well, probably the other way around since java came first, but C# has outdone java imo)

  12. #12
    Join Date
    Feb 2011
    Posts
    5

    Re: Stack Overflow Error?

    Quote Originally Posted by ThermoSight View Post
    Truncating the format string (or providing the additional operands) may help ...

    Code:
    "{0}: {1} {2}: \n{3}: {4}\n{5}: {6} \n{7}: {8}\n{9}: {10}: \n{11}: {12} \n{13:F2}: {14} \n{15:C}: {16}",
    I lopped off everything after {8}\n and it ran to completion .... did you forget to add the operands to support the format ?....
    So wait, you closed the entire program after {8}/n ? What exactly did you edit out..can you post the code chunk that compiled for you?




    Quote Originally Posted by BigEd781 View Post
    Yeah, they didn't know what they were talking about . The biggest similarity between C# and C++ is the syntax, pretty much everything else is different. You would have had the same issue going to java, which is similar in many ways to C# (well, probably the other way around since java came first, but C# has outdone java imo)
    Bah! I'm a EE major as it is, but I still somewhat enjoy programming (I'm a network engineer by trait so coding always kinda seemed foreign to me) but C++ was WAY easier to pickup!

  13. #13
    Join Date
    Oct 2005
    Location
    Seattle, WA U.S.A.
    Posts
    353

    Re: Stack Overflow Error?

    Oh Boy am I ever embarrassed !


    Yup, you were right to question my action. Yeah, lopping off everything after the 8}\n would fix it too, but that is excessive. The real problem was the {16}, so i changed it to ...
    "{0}: {1} \n{2}: {3}: \n{4} {5}: \n{6} {7}: \n{8} {9}: \n{10}: {11}: \n{12} {13:F2}: \n{14} {15:C}\n ",

    that's what happens when one makes a change and doesn't even give it a second thought (some might say "or even a first thought")

    thank you for pointing out my error.
    Last edited by ThermoSight; February 7th, 2011 at 11:12 PM.

  14. #14
    Join Date
    Jan 2010
    Posts
    1,133

    Re: Stack Overflow Error?

    Quote Originally Posted by BigEd781 View Post
    [...] but C# has outdone java imo
    He, he, he... If some of those Java developers who feel Microsoft is the root of all evil ever get a hold of you...

  15. #15
    Join Date
    Feb 2011
    Posts
    5

    Re: Stack Overflow Error?

    Quote Originally Posted by ThermoSight View Post
    Oh Boy am I ever embarrassed !


    Yup, you were right to question my action. Yeah, lopping off everything after the 8}\n would fix it too, but that is excessive. The real problem was the {16}, so i changed it to ...
    "{0}: {1} \n{2}: {3}: \n{4} {5}: \n{6} {7}: \n{8} {9}: \n{10}: {11}: \n{12} {13:F2}: \n{14} {15:C}\n ",

    that's what happens when one makes a change and doesn't even give it a second thought (some might say "or even a first thought")

    thank you for pointing out my error.
    Thermo, I really appreciate this!

    Here is my REAL question (to all you guys)..

    As I said before, I'm an Engineering major and I am in part 2 of my programming sequence. Part 1 was just C++ all the way up to structs, now in semester 2 of the sequence you can either take Java, more C++ or C#.
    I work full time and the only class I could get into was the C# class. Are there any forums/link/books that I can take up that will help ease the conversion from C++ to C#? Our professor talks like he expects us to understand this already and I just want to get through this course!

    Thanks again guys!

Page 1 of 2 12 LastLast

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  





Click Here to Expand Forum to Full Width

Featured