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

    problem with global variables in Visual Studio 2010

    I know globals are generally a bad idea, I just use them for debugging purposes on occasion.

    I have a global variable that is clearly (I checked this multiple times, in multiple ways) not being accessed by any other part of the program. But the value of the variable is being modified somehow, from time to time.

    Here is whats happening. My code looks something like this:

    Code:
    bool my_debug_flag=true; // global 
    
    ...
    
    void myclass::somefunction(char* info) 
    {
          if (my_debug_flag)
          {
              printf(info);
              
           }
    
           my_debug_flag=false;
    }
    The idea is that somefunction() will print 'info' only the first time it is called. But what happens instead, is it prints info every time it is called.

    So I upped the ante and made the debug flag a private member of a class.

    Code:
    class MyDebugClass
    {
       public:
       MyDebugClass() { flag=true; } 
       bool getFlag() const { return flag; }
       void setFlag(bool _flag) { flag=_flag; }
       private:  
       bool flag;
    };
    
    ...
    
    MyDebugClass * debug; // global
    
    ...
    
    
    void myclass::somefunction(char* info) 
    {
          if (debug->getFlag())
          {
              printf(info);
              
           }
    
           debug->setFlag(false);
    }
    
    ...
    
    main()
    {
       debug = new DebugClass();
       ...
    
    }
    But the same behavior occurs. Somefunction prints info every single call. It appears as if flag is somehow being set to true again. However, if flag is initially set to false in the constructor, it is never reset to true.

    I'm trying to list possible reasons for why this could be happening. My best guess right now is memory corruption. In particular, perhaps writing past the end of an array. But if this were happening, why would it reset to true only if it was initially set to true?

    What other possibilities should I consider? Any suggestions for how to tackle this strange bug?

  2. #2
    GCDEF is offline Elite Member Power Poster
    Join Date
    Nov 2003
    Location
    Florida
    Posts
    12,635

    Re: problem with global variables in Visual Studio 2010

    Set a break point on the variable with the condition "has changed" so it will tell stop when something changes the value.

  3. #3
    Join Date
    Feb 2008
    Posts
    53

    Re: problem with global variables in Visual Studio 2010

    Thanks for the response, but after a recent experiment, I think it may have something to do with threading.

    My project is a win32 application and I used "SetTimer(..., update(...))" to set the frame rate and call update() every frame. The function 'somefunction' I mentioned earlier is called by this update() function.

    Recall the definition of somefunction is:

    Code:
    void myclass::somefunction(char* info) 
    {
          if (my_debug_flag) // my_debug_flag is global
          {
              printf(info);
              
           }
    
           my_debug_flag=false;
    }
    I moved somefunction to be called by a function outside of update() and it reset the global variable appropriately. I tried creating a separate project with these barebone features, and the same behavior occured.

    I don't know much about threading, but my guess is SetTimer is creating a separate thread, and that is somehow screwing up the global variables. Does this sound like a reasonable argument? Why would an additional thread cause this strange behavior?

  4. #4
    VictorN's Avatar
    VictorN is offline Super Moderator Power Poster
    Join Date
    Jan 2003
    Location
    Hanover Germany
    Posts
    20,396

    Re: problem with global variables in Visual Studio 2010

    Quote Originally Posted by Mikau View Post
    I don't know much about threading, but my guess is SetTimer is creating a separate thread, and that is somehow screwing up the global variables. Does this sound like a reasonable argument? Why would an additional thread cause this strange behavior?
    No, SetTimer does not create any separate thread.
    Victor Nijegorodov

  5. #5
    VictorN's Avatar
    VictorN is offline Super Moderator Power Poster
    Join Date
    Jan 2003
    Location
    Hanover Germany
    Posts
    20,396

    Re: problem with global variables in Visual Studio 2010

    Quote Originally Posted by Mikau View Post
    I have a global variable that is clearly (I checked this multiple times, in multiple ways) not being accessed by any other part of the program. But the value of the variable is being modified somehow, from time to time.
    Could you create a very small test project reproducing this behavior and post it to Forum (in zip archive not including Debug/Release subfolders nor .aps, .sdf, .opt, .clv files?
    Victor Nijegorodov

  6. #6
    Join Date
    Oct 2006
    Location
    Sweden
    Posts
    3,654

    Re: problem with global variables in Visual Studio 2010

    See also my post in your original thread http://forums.codeguru.com/showthrea...010&highlight= regarding data breakpoints
    Last edited by S_M_A; August 27th, 2012 at 10:57 AM.
    Debugging is twice as hard as writing the code in the first place.
    Therefore, if you write the code as cleverly as possible, you are, by
    definition, not smart enough to debug it.
    - Brian W. Kernighan

    To enhance your chance's of getting an answer be sure to read
    http://www.codeguru.com/forum/announ...nouncementid=6
    and http://www.codeguru.com/forum/showthread.php?t=366302 before posting

    Refresh your memory on formatting tags here
    http://www.codeguru.com/forum/misc.php?do=bbcode

    Get your free MS compiler here
    https://visualstudio.microsoft.com/vs

  7. #7
    Join Date
    Apr 1999
    Posts
    27,449

    Re: problem with global variables in Visual Studio 2010

    Quote Originally Posted by Mikau View Post
    I'm trying to list possible reasons for why this could be happening. My best guess right now is memory corruption. In particular, perhaps writing past the end of an array. But if this were happening, why would it reset to true only if it was initially set to true?
    Honestly, you should stop guessing and get on the job of debugging. Guessing only wastes time. Once you corrupt memory, anything can happen.

    When you have memory corruption (which you do have, regardless of the reason), it's time to debug the program.
    What other possibilities should I consider?
    Memory corruption happens in any multitude of ways, from out of bounds access to just plain old bad C++ coding that just happens to compile "OK".
    Any suggestions for how to tackle this strange bug?
    First, that bug is not strange.

    As to tackling the problem, you tackle it by setting a data breakpoint and wait to see what changes the value.

    Regards,

    Paul McKenzie

  8. #8
    Join Date
    May 2009
    Posts
    2,413

    Re: problem with global variables in Visual Studio 2010

    Quote Originally Posted by Mikau View Post
    What other possibilities should I consider? Any suggestions for how to tackle this strange bug?
    I would try a Singleton and specifically a so called Meyer's Singleton. It won't help against synchronization issues but otherwise it should fix your problem.

    You introduce a .h and a .cpp file, say mydebugclass.h and mydebugclass.cpp. On mydebugclass.h you put this,

    Code:
    #ifndef MYDEBUGCLASS_ONCE
    #define MYDEBUGCLASS_ONCE
    
    class MyDebugClass {
    public:
       MyDebugClass() : flag(true) {} 
       bool getFlag() const { return flag; }
       void setFlag(bool _flag) { flag=_flag; }
    private:  
       bool flag;
    };
    
    MyDebugClass& DEBUG(); // a Meyer's Singleton
    
    #endif
    And on mydebugclass.cpp you do this,

    Code:
    #include "mydebugclass.h"
    
    MyDebugClass& DEBUG() { // a Meyer's Singleton implementation
       static MyDebugClass mdc;
       return mdc;
    }
    You use it like say,

    Code:
    #include "mydebugclass.h"
    
    // ......
    
       DEBUG().setFlag(true);
       if (DEBUG().getFlag()) {
          // ...
       }
    
    // ......
    Good luck.
    Last edited by nuzzle; August 24th, 2012 at 02:32 AM.

  9. #9
    Join Date
    Jul 2005
    Location
    Netherlands
    Posts
    2,042

    Re: problem with global variables in Visual Studio 2010

    Quote Originally Posted by Mikau View Post
    I have a global variable that is clearly (I checked this multiple times, in multiple ways) not being accessed by any other part of the program. But the value of the variable is being modified somehow, from time to time.

    Here is whats happening. My code looks something like this:

    Code:
    bool my_debug_flag=true; // global 
    
    ...
    
    void myclass::somefunction(char* info) 
    {
          if (my_debug_flag)
          {
              printf(info);
              
           }
    
           my_debug_flag=false;
    }
    Where is this code located? Particularly the definition of the global variable.
    Quote Originally Posted by Mikau View Post
    I'm trying to list possible reasons for why this could be happening. My best guess right now is memory corruption. In particular, perhaps writing past the end of an array. But if this were happening, why would it reset to true only if it was initially set to true?

    What other possibilities should I consider? Any suggestions for how to tackle this strange bug?
    I see two possible reasons for this bug: either you are accessing different variables, or the variable is set to true by your program. I'd suggest to first check if you are accessing the same variable by checking its address in the debugger. If that's the case, then use the debugger to check when that memory is changed (as others have suggested).
    Cheers, D Drmmr

    Please put [code][/code] tags around your code to preserve indentation and make it more readable.

    As long as man ascribes to himself what is merely a posibility, he will not work for the attainment of it. - P. D. Ouspensky

  10. #10
    Join Date
    Jul 2005
    Location
    Netherlands
    Posts
    2,042

    Re: problem with global variables in Visual Studio 2010

    Quote Originally Posted by nuzzle View Post
    I would try a Singleton and specifically a so called Meyer's Singleton. It won't help against synchronization issues but otherwise it should fix your problem.
    ...
    Strictly speaking that's not a singleton, because it's possible to create multiple instances of the class.
    Also, I would advice against trying to fix a problem that is not understood. If the actual cause of the problem is some memory corruption, then using a singleton won't fix anything.
    Cheers, D Drmmr

    Please put [code][/code] tags around your code to preserve indentation and make it more readable.

    As long as man ascribes to himself what is merely a posibility, he will not work for the attainment of it. - P. D. Ouspensky

  11. #11
    John E is offline Elite Member Power Poster
    Join Date
    Apr 2001
    Location
    Manchester, England
    Posts
    4,835

    Re: problem with global variables in Visual Studio 2010

    Code:
    prinf(info);
    Check the specification for printf(). printf(info); is not valid code. You must specify the data format to be printed, along with the actual data. You probably meant printf("%s", info);

    printf() isn't very intelligent. You must give it exact instructions about what to print. In particular, if you fail to specify the format correctly or you supply the wrong number of arguments (or if you specify a particular type of variable but then you supply a different kind) printf's behaviour is undefined. It can (and usually does) crap all over something else.
    "A problem well stated is a problem half solved.” - Charles F. Kettering

  12. #12
    Join Date
    Jul 2002
    Posts
    2,543

    Re: problem with global variables in Visual Studio 2010

    Quote Originally Posted by John E View Post
    printf(info); is not valid code.
    Why? What about printf("hello") ?

    On the other hand, if info contains printf format specifications, results may be surprising... But I don't believe that memory is corrupted here.
    Last edited by Alex F; August 27th, 2012 at 08:52 AM.

  13. #13
    VictorN's Avatar
    VictorN is offline Super Moderator Power Poster
    Join Date
    Jan 2003
    Location
    Hanover Germany
    Posts
    20,396

    Re: problem with global variables in Visual Studio 2010

    According to MSDN example
    printf("Line one\n\t\tLine two\n");
    this code is valid.
    As well as what OP used.
    The problem would arise if this info contained some format specification though:
    Quote Originally Posted by MSDN
    The results are undefined if there are not enough arguments for all the format specifications.
    Victor Nijegorodov

  14. #14
    John E is offline Elite Member Power Poster
    Join Date
    Apr 2001
    Location
    Manchester, England
    Posts
    4,835

    Re: problem with global variables in Visual Studio 2010

    Perhaps I should say that the code as written may not result in sensible behaviour. It all depends on what info actually contains.
    "A problem well stated is a problem half solved.” - Charles F. Kettering

  15. #15
    John E is offline Elite Member Power Poster
    Join Date
    Apr 2001
    Location
    Manchester, England
    Posts
    4,835

    Re: problem with global variables in Visual Studio 2010

    Quote Originally Posted by Alex F View Post
    if info contains printf format specifications, results may be surprising... But I don't believe that memory is corrupted here.
    Alex, I think there's a pretty good chance it might be. I've known printf() to corrupt memory simply because I mistakenly passed an int (4 bytes) when a char (1 byte) was expected.!

    Maybe someone here can confirm or refute this but AFAIK the compiler's normal casting gets bypassed for variable argument lists. At least, I've always found it very dangerous to rely on casting in that situation.
    "A problem well stated is a problem half solved.” - Charles F. Kettering

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