I suspect I have found a g++ optimization bug which relates to dereferencing arrays in objects (structs) with negative indexes.
In the below, Node is structure which has an array preceding it (in my real code it is a node for a Skip List where both its number of pointers and the size of its data packet are variable and unknown to the underlying SkipList code, hence a decision to put the pointers before the object reference and the data packet - here a long - after the object).
#include <iostream>
#include <stdlib.h>
class Node {
public:
unsigned int ptr[1]; // really an array going backwards
long datum; // This seems to be necessary for the bug to surface
};
class NodeList {
public:
Node* hdr;
NodeList() {
void* p_v = malloc( sizeof(Node) + 32 * sizeof( unsigned int ) );
hdr = (Node*)((char*)p_v + 32 * sizeof(unsigned int));
hdr->ptr[-5]=100;
}
void setNodes() {
int nn=0;
while( rand() > 20 && nn<9 ) {
nn++;
}
if( nn < 9 ) {
nn = 9;
}
// It is a logical truth that nn = 9 here
//nn = 9; // IF THIS IS UNCOMMENTED EVERYTHING WORKS!
std::cout << "nn=" << nn << " (should be 9) " << std::endl;
int ctr = 0;
for( int i=0; i<=nn; i++ ) {
ctr++;
hdr->ptr[-i]=0;
}
std::cout << "ctr was incremented " << ctr << " times (should be 10) and hdr->ptr[-5] = " << hdr->ptr[-5] << " (should be 0)\n";
}
};
int main( int argc, char** argv ) {
NodeList list;
list.setNodes();
}
Expected output has ctr being incremented 10 times and hdr->ptr[-5] being 0. Optimized code just goes through the loop once (ie does not loop), and leaves ptr->hdr[-5] as 100. This is a bug.
-fno-aggressive-loop-optimizations seems to fix it but clearly would be better if the output code was correct.
I am putting this here to (a) get verification that this is a bug since I am a newbie here and this is my first question, (b) ask anyone knowledgeable in the gcc dev community what is to be done about it (eg. how should I report it, and whether it has been fixed in later releases), and (c) to allow folk who have experienced this most frustrating and time-consuming issue on CentOS 7 (or any other distro with 4.8) to see confirmation that they have hit a bug from a fellow sufferer!