5

I tried to define a global array, named _end, of size ~1000 in C/C++, but I got a segmentation fault even when I simply iterated it. Is the name "_end" very special in C/C++ that causes such problem? Or this can be a very serious bug... (The code is attached below, and it breaks in g++ 4.3.2, 4.5.2, 4.9.2, etc.)

#include <iostream>
using namespace std;

int _end[1111];

int main() {
    for (int i=0; i<1111; i++) {
        cout << i << endl;
        _end[i]++;
    }
    return 0;
}

You can see the result at https://ideone.com/XAcUeZ. See here also for the C compiler.

Blue Bear
  • 53
  • 5
  • @AlterMann Well that won't explain a segfault for me obviously? – πάντα ῥεῖ May 01 '15 at 16:22
  • 1
    works in my environment ... maybe ideone.com sucks? – Grady Player May 01 '15 at 16:22
  • and you should remove the C tag – Grady Player May 01 '15 at 16:23
  • 1
    Maybe it differs by compilers? I will add the compiler information. – Blue Bear May 01 '15 at 16:30
  • 1
    Looks like `_end` is defined as something else on your platform (it's a [reserved name](http://stackoverflow.com/a/228797/21475), after all). – Cameron May 01 '15 at 16:32
  • 2
    I've noticed it works well, as soon you place `int _end[1111] {0};` inside of main's body: https://ideone.com/zT9ZII It's strange behavior I agree. Seems to have something to do with initialization of `_end`. Also using prefix `_` for symbols might call strange side effects, as these are actually reserved for implementation. – πάντα ῥεῖ May 01 '15 at 16:35
  • _end is in the global namespace and according to the standard (17.6.4.3.2 Global names) "Each name that begins with an underscore is reserved to the implementation for use as a name in the global namespace". For instance, _end might be used to to mark the address of the end of the data sections. – Come Raczy May 01 '15 at 16:38

1 Answers1

5

Names which start with an underscore (or two) are reserved for the compiler. This is official C++ standard. Use at own risk.

Greenflow
  • 3,935
  • 2
  • 17
  • 28
  • 5
    With GCC in particular, [_end is a pointer to the end of the program](http://man7.org/linux/man-pages/man3/end.3.html). Changing the name of the variable makes the program work. – Joey Adams May 01 '15 at 16:32
  • See also this answer which discusses C++'s rules around reserved identifiers: https://stackoverflow.com/a/228797/ – Max Barraclough Nov 17 '19 at 16:47