(Non) Static Object in Loop

In a book there is an example about static/non-static objects.

char buf[MAX]; long count=0; int i=0; while(i++<=MAX) if(buf[i]=='') { buf[i]='*'; ++count; } assert(count<=i);

It is said that sometimes the code will write past the end of the buf array into count and make the assertion to fail. And then tells about declaring count as static and solve the problem (note: the author gives this as a bad solution example) Anyway, apart from being a bad example, I cannot figure out how the problem happens, and how it is solved as declaring count as static.

-------------Problems Reply------------

The example counts on a specific layout of the variables in memory, namely that count comes just after buf. By making count static, it gets placed in a different part of memory and something else gets clobbered instead. The problem didn't go away, the symptoms just changed.

It's not only a bad solution, it's a non-solution. You can't index over an array's bounds. If you do, you have a non-solvable problem with regard to achieving a correct C++ program.

What you might see on common C++ implementations is that sometimes count is put into the stack directly after buf. So if you over-index and then write, you may modify count and then any assumption on the value of count that is based purely on direct writes to it isn't correct anymore because there is a write to it by that over-index operation.

If you now make it static the variable then is allocated in some other section of the program (usually the .bss for 0-initialized and .data for otherwise initialized data), the count variable on common implementations won't be allocated next to the array anymore and this will cause another incident to happen: Instead of overwriting count you may then be overwriting whatever is then next to the array.

Johannes' answer is correct.

However, as to why declaring count as static might make it appear to work. When count is declared as non-static, it will typically live immediately after buf[] in memory (on the stack). However, when declared as static, it will not be on the stack, and so will not be corrupted when you write past the end of buf[].

I concur, if you exceed an arrays bounds you cause an out of bounds exception. Or in non managed languages like C/C++ you could end up writing/reading into the next lot of memory address, of the memory of my non null terminated string running off into another objects memory wasn't fun.

I am somewhat curious to where is your static object, you declare them all as variables, there is no static object in sight.

The above code should always exceed the array as i is checked against max first, then i is increased which puts i one more than max, giving you an off by 1 error.

I'd like to read the book, but I imagine it's displaying examples of "Voodoo Programming", where you try random stuff until it stops breaking, and call that a success.

As mentioned elsewhere, all you'd do by declaring it static is move count to a different place, which would mean that the assert might pass. To an inexperienced programmer, that would be enough to submit, at which point you have buffer overrunning code in your production environment.

Of course, I'd expect that "i" would then be overwritten, which would be even worse as it's a control variable for the loop, but I could be wrong about that.

Category:c# Views:1 Time:2010-09-03
Tags: c# static

Related post

  • Using static objects 2009-09-26

    My understanding is any method which does not modify state of the constaining class is a prime candidate to be made static because it does not touch the instance. An instance would be that containing class's data (fields/properties) so if I had a per

  • Why does setting a static object cause my method calls to abort? 2011-09-19

    I have a WPF application which contains 4 tabs. Tab1 is the first tab loaded with the application. I have a Tab1Load method (the name of the tab) which looks like: private void Tab1Load(object sender, RoutedEventArgs e) { myConfig.LoadConfigurationDa

  • Is it possible to create function-static objects programmatically? 2012-02-16

    I need to create a vector which holds the pointers to some static objects (e.g., a1, a2, a3). void foo() { static TEST a1, a2, a3; static vector<TEST *> m_test; m_test.push_back( &a1 ); m_test.push_back( &a2 ); m_test.push_back( &a3

  • Lock on static object from within a delegate is not working 2012-03-27

    How come this isn't working? private static object Lock_HandleError = new object(); public static void HandleError(Exception ex) { lock( Lock_HandleError ) { //IF the UI is processing a visual tree event (such as IsVisibleChanged), it throws an excep

  • Static destruction of local-static object 2012-04-27

    Help me understand this... see bold. From the Standard 3.6.3 Termination (2) 2 If a function contains a block-scope object of static or thread storage duration that has been destroyed and the function is called during the destruction of an object wit

  • Initializing static objects - Code design question 2008-10-09

    In my webapplication (C#, .Net 3.5), made up of a core class library (containing the business logic, data layer and a couple of utility classes), a windows service project, a webservice project and the website project, I have a couple of static class

  • How can I animate a static object in a WPF storyboard 2008-12-18

    I have a WPF program to which I need to add a "Demo mode". Since I want my designers to be able to modify the demo mode without me having to recompile the program each time, I tough it would be a great idea to use a storyboard from an external XAML f

  • Destruction order of static objects in C++ 2009-01-22

    Can I control the order static objects are being destructed? Is there any way to enforce my desired order? For example to specify in some way that I would like a certain object to be destroyed last, or at least after another static object? ----------

  • Using static objects in XAML that were created in code in Silverlight 2009-03-12

    I couldn't get this to work in Silverlight, so I created two test projects. One simple WPF project and one simple Silverlight project that both do only one thing: set a public static readonly variable in code, and use it in a completely bare bones XA

  • What are the reasons for preferring Singleton or function scope local static objects over one another? 2009-04-10

    Both Marshall Clines' "C++ FAQ Lite" and Scott Meyers' Effective C++ suggest using functions returning local static objects to avoid possible problems with non-local static object initialization order. In short (from "Effective C++", 3rd edition by S

  • C# Using block usage with static objects 2009-04-15

    I'm adding some code into a using block in a C# program. I'm sort of stuffing my app, which previously was a standalone into an existing body of code, so I need to do a bit of messing around to get it to fit properly. What it's ending up looking like

  • static constructors in C++? need to initialize private static objects 2009-07-28

    I want to have a class with a private static data member (a vector that contains all the characters a-z). In java or C#, I can just make a "static constructor" that will run before I make any instances of the class, and sets up the static data member

  • How can I create a static object member of class? 2009-08-29

    I am fairly new to c++, especially in its techniques. My question is, how can I create a static object member of a class itself. What I mean is I declared a static member object inside a class. Example: CFoo:CFoo *pFoo[2] = {0}; class CFoo { public:

  • C++ singleton vs. global static object 2009-09-23

    A friend of mine today asked me why should he prefer use of singleton over global static object? The way I started it to explain was that the singleton can have state vs. static global object won't...but then I wasn't sure..because this in C++.. (I w

  • Arranging global/static objects sequentially in memory 2009-09-28

    In C++, is it possible to force the compiler to arrange a series of global or static objects in a sequential memory position? Or is this the default behavior? For example, if I write… MyClass g_first (“first”); MyClass g_second (“second”); MyClass g_

  • Crash at static object destruction 2009-12-28

    I am working on a 3rd party c++ app. It is crashing during the exit. If I look at the stack all I get is the __static_initialization_and_destruction_0 function and lots of questions marks. Project is huge and unfortunately it has many static objects.

  • Static objects in wpf app 2010-02-11

    In my wpf app i am using a lot of objects declared as static for caching purposes. Just wondering if there are any drawbacks. --------------Solutions------------- I almost never use static data, because of the inherent problems that come into play wh

  • Is it safe to access asp.net session variables through static properties of a static object? 2010-05-10

    Is it safe to access asp.net session variables through static properties of a static object? Here is what I mean: public static class SessionHelper { public static int Age { get { return (int)HttpContext.Current.Session["Age"]; } set { HttpContext.Cu

  • What is the correct way to synchronize a shared, static object in Java? 2010-06-09

    This is a question concerning what is the proper way to synchronize a shared object in java. One caveat is that the object that I want to share must be accessed from static methods. My question is, If I synchronize on a static field, does that lock t

Copyright (C) dskims.com, All Rights Reserved.

processed in 0.143 (s). 11 q(s)