Reputation: 458
I have some troubles to understand the order of execution of a c++ program. I have a program with a bufferoverflow. But the thing that is strange is that the segfault (due to the bufferoverflow) happens in the code some lines before the bufferoverflow.
My program is as follow:
//Some code ...
file.seekg(0, std::ios::end);
auto file_size = file.tellg();
file.seekg(0);
std::vector<uint8_t> buffer(file_size);
//Some code
char t[1];
t[2] = 1;
//Some code
So the affectation t[2] = 1
generates a bufferoverflow. But the segfault happens during the initialization of the vector. The file_size
is well computed but when std::vector<uint8_t> buffer(file_size)
is executed, file_size
becomes -1 (generating a segfault). This segfault is generated by the bufferoverflow. If I removed the statement t[2] = 1
, every works well.
So my question is how the segfault can happen before the execution of the bufferoverflow? The execution of code can be altered by the compiler?
Upvotes: 1
Views: 97
Reputation: 63471
So my question is how the segfault can happen before the execution of the bufferoverflow? The execution of code can be altered by the compiler?
The compiler is free to rearrange initialisation of unrelated data on the stack. There is no logical relationship between your vector and the array, and so the compiler can decide to reorder the initialisation if it chooses.
But you have invoked undefined behaviour by overflowing your array bounds. That means you have violated any assumptions made by the compiler about how it can reorder memory or code. So all bets are now off. Anything can happen, even if it doesn't make sense.
Upvotes: 3