Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Segmentation fault on returning from main (very short and simple code, no arrays or pointers)

Tags:

c++

I've been wondering why the following trivial code produces a segmentation fault when returning from main():

//Produces "Error while dumping state (probably corrupted stack); Segmentation fault"

#include <iostream>
#include <fstream>
#include <vector>
using namespace std;

class Test
{
    vector<int> numbers;
};

int main()
{
    Test a;
    ifstream infile;

    cout << "Last statement..." << endl; // this gets executed
    return 0;
}

Interestingly, 1) if only one of the two variables is declared, I don't get the error, 2) if I declare a vector variable instead of an object with a vector member, everything's fine, 3) if I declare an ofstream instead of an ifstream, again, everything works fine. Something appears to be wrong with this specific combination...

Could this be a compiler bug? I use gcc version 3.4.4 with cygwin.

Thanks for the tips in advance.

Gábor

like image 533
Gábor Kovács Avatar asked Jan 15 '11 23:01

Gábor Kovács


People also ask

How do I find out what is causing my segmentation fault?

Use debuggers to diagnose segfaults Start your debugger with the command gdb core , and then use the backtrace command to see where the program was when it crashed. This simple trick will allow you to focus on that part of the code.

What are three kinds of pointers that can cause a segmentation fault?

Causes of segmentation fault:Attempting to access a nonexistent memory address (outside process's address space). Attempting to access memory the program does not have rights to (such as kernel structures in process context). Attempting to write read-only memory (such as code segment).

What causes segmentation fault with pointers?

A segmentation fault usually occurs when you try to access data via pointers for which no memory has been allocated. It is thus good practice to initialize pointers with the value NULL, and set it back to NULL after the memory has been released.


1 Answers

This is a bug. If this is your entire program, there is absolutely nothing wrong with it. You have discovered a bug in the compiler or standard library. As was recommended to you in the comment, try a 4.x series gcc compiler. The 3.x series is old as the hills.

like image 125
Omnifarious Avatar answered Nov 07 '22 09:11

Omnifarious