Consider the following code
#include <chrono>
#include <iostream>
#include <random>
#include <vector>
class TestClass
{
public:
int A = 0;
int B = 4;
protected:
private:
};
int main(int argc, const char * argv[])
{
std::random_device randomDevice;
std::mt19937 mersenneTwister(randomDevice());
std::uniform_int_distribution<size_t> distribution(1,255);
for (size_t i=0; i<10000000; ++i)
{
size_t const vectorSize = distribution(mersenneTwister)+1;
TestClass* testVector(reinterpret_cast<TestClass*>(malloc(vectorSize*sizeof(TestClass))));
if (testVector[0].A == 0x0ffeefed)
{
std::cout << "Sorry value hit." << std::endl;
break;
} /* if */
free(testVector);
} /* for */
return 0;
}
Clang completely removes the for-loop with optimisation -O3. I am a bit surprised. Although testVector will contain only garbage, I expected the loop not to be removed (actually also no warning was issued, only the analyser detected that testVector contains garbage).
If I add a line assigning a value to a random element of testVector, the loop is not removed.
PS: I wanted to use the loop for testing the execution speed of malloc and free.