Segmentation error, how to find out the cause

Hi, I have a segmentation error when I run my programme. In order to find out where this comes from, I added lines like

cout<<"still";

to see until what point the error has not yet occurred. But for two consecutive lines of "cout<<...", only the first line is printed, and then I get this "segmentation error" message. I don't understand how that happens. Does the program run normally before the error occurs and stops once it does? If not how can I locate the problem? Thanks!
Yes, an application will run right up until it hits the run time error (seg-faults are run-time errors). You would normally find run-time errors with a debugger, but seg-faults can be easy to spot, especially in beginner code. By far the most common mistake is over running an array's index within a loop, so double check your loops and make sure you aren't doing that. The next most common I would say is trying to de-reference an uninitialized pointer, so make sure any pointers you are using are actually pointing to something. Next most probable is trying to use a reference to an item that has expired, unless you have a pretty solid knowledge of how an objects life-time works in C++, you may want to start using a debugger at this point. After that the mistakes are more or less as common as one and other.

You could always post some code and let one of us take a look at it.
Writes to std::cout is buffered. Tht means that anything written into it is not immediatly output to screen. Usually input buffer is flushed when you explicitly do so, when you asking for input, when buffer is full and in some other cases.

You can use unbuffered std::cerr for that. Or use a debugger. It will give you much more info than randomly placed output would.
Thanks Computergeek01 and MiiNiPaa! I have already found the bug. Thanks for the explanation of input buffer, I was really perplexed it.

I use g++ on Ubuntu to complie and run my code. I haven't figured out how to debug with it yet...
$ g++ -ggdb foo.cpp
$ gdb a.out
> run
(Seg fault)
> backtrace
there you would get the line where it crashed (that is not necessarily the same that the line that it caused said crash)
you could then inspect your variables looking for invalid of unexpected values.

Another powerful tool is `valgrind', that may detect use of initialized data and out of bounds access.

If you are using std::vector, make operator[] check out of bounds
$ g++ -D_GLIBCXX_DEBUG

http://www.cplusplus.com/forum/unices/60864/#msg332274
Thanks! I'll try it next time.
Topic archived. No new replies allowed.