I don't understand why this code fails at runtime, it compiles with no errors and no matter how much I review the code I don't see why a segmentation fault
: should jump out.
#include <iostream>
constexpr std::size_t BUFF_SIZE { 256u };
int buffer[BUFF_SIZE] {};
int *_begin = buffer;
int *_end = buffer + (BUFF_SIZE / 2u);
int main()
{
for (unsigned indice{}; indice < (BUFF_SIZE / 2u); ++indice) {
*(_begin + indice) = indice;
*(_end + indice) = (BUFF_SIZE / 2u) - indice;
}
for (const auto &v : buffer) std::cout << v << '\n';
return 0;
}
You can see the code working [here] .
Problem.
The problem is that
_begin
and_end
are not advisable names to use in variables.Names beginning with an underscore (
_
), while not being keywords in the C++ language, are reserved for use by compilers, so using them can interfere with their operation.What happened?.
For example, the compiler
gcc
(used in the failing code) declares the symbols_etext
,_edata
and_end
(my translation):_end
Surely the compiler prompt has hidden the variable_end
and an attempt has been made to modify a memory address that we should not have access to, giving rise to thesegmentation fault
.Technical details.
The C++ standard states that compilers can use variables beginning with an underscore (
_
) at their convenience:In the section
§2.10
(translation and highlighting are mine):The standard itself indicates that no diagnosis is required in case an identifier considered as reserved is used in the code. This means that unlike keywords that raise a compiler error if used as identifiers, reserved identifiers do not raise a compiler error or alarm when used in code.
Solution.
Do not use the underscore (
_
) to name variables or macros:The above code prints: