Silverfrost Forums

Welcome to our forums

Access Violation in C++, address variable changes

29 Sep 2020 8:14 #26419

An odd bug where a guard clause around a loop causes the code work. Without it we get an access violation. I did not report this when I first found it as I managed to work around it using the below but it has now cropped up somewhere else in the same codebase and the same workaround can be used.

I did output (to a message box) the address and value of the variable to verify this. This will be a terrible one to isolate as the codebase is large and not well formed. I mention it in case it rings any bells as it would be good to get to the bottom of.

  /* Don't remove the following conditional, it works around an issue in 64 bit.
  ** If you check the address of the_number before this loop and then after
  ** this loop, it changes. It gets restored on exit of the routine though.
  ** Placing this conditional here gets the compiler to not do whatever it was
  ** doing and the address stays the same, meaning no crashes.
  */
  if (the_number > 0)
  {
    for(int i = 0; i <the_number; i++) {
      the_elements_backup[i] = the_elements[i];
    }
  }

Happy to share more info if you are interested.

30 Sep 2020 9:11 #26420

Ryan

Thank you for the feedback. I can't see anything wrong with the assembly listing for my test program. Is the_number a simple local variable?

Here is my test code...

  #include <stdio.h>
  int main()
  {
     int the_number = 0;
     int the_elements_backup[4], the_elements[4];
     int* p = &the_number;
     for(int i = 0; i < the_number; i++)
     {
        the_elements_backup[i] = the_elements[i];
     }
     printf('%p %p\n', p, &the_number);
     return 0;
  }
30 Sep 2020 9:55 #26421

Nothing so simple, it's a Template (below, reduced for simplicity).

template <class Type>
class database {
public:
  database(int);
  int the_number;
private:
  Type *the_elements;
  Type *the_elements_backup;
};
30 Sep 2020 10:55 #26422

Ryan

My understanding is that no attempt has yet been made to get C++ templates to work for 64 bits.

30 Sep 2020 11:14 #26423

Understood. They work, but old code so I'm loathe to touch them. I'll see if there is an alternate approach to templates.

Thanks Paul

Please login to reply.