E
E
eLBeatzzz2014-03-13 15:25:51
C++ / C#
eLBeatzzz, 2014-03-13 15:25:51

What's the weird workaround for GCC with volatile?

Hello!
I stumbled upon a snippet in the old code, like... well, just in the old code that I can't make sense of. This uses a workaround for GCC, again an unknown version. The actual NDA-obfuscated code (note the excellent comment carefully left by the author of the code):

struct A
{
  int _a;
  int _b;
  A(int a, int b) : _a( a ), _b( b ) {}
};

vector<A> a_storage = fill_a_storage();
vector<size_t> a_index = get_a_index();

A get_a(size_t index)
{
#ifndef __GNUC__
  return a_storage[ a_index[index] ];
#else   // Workaround for the GCC compiler
  volatile A tmp = a_storage[ a_index[index] ];
  return A(tmp._a, tmp._b);
#endif
}

I would be eternally grateful if someone could explain the essence of this workaround with a temporary volatile variable:
#else   // Workaround for the GCC compiler
  volatile A tmp = a_storage[ a_index[index] ];
  return A(tmp._a, tmp._b);
#endif

Answer the question

In order to leave comments, you need to log in

1 answer(s)
I
Ivan Starkov, 2014-03-13
@eLBeatzzz

Very similar to the situation here https://bugzilla.redhat.com/show_bug.cgi?id=90131
"gcc-3.2.2 corrupts structs if several struct-copy operations are performed in
sequence"
There are other similar examples on the links, everywhere the proposed workaround is to insert a compiler ban on reorder commands - asm("") (or asm volatile("" ::: "memory");)
Here, the same problem is probably solved through volatile X x = y and subsequent copying of the structure, the author may uses something like "A compiler cannot eliminate or reorder reads/writes to a volatile-qualified variables"

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question