vector::size and Segmentation fault - c++

Why could this code throw segmentation fault?:/
listeners = new vector<Listener*> ();
... /* other code */
if (listeners != NULL) {
int i = listeners->size();
}

Just because the pointer isn't NULL doesn't mean it points to a valid vector<Listener*> object.
Run your program through valgrind to detect memory corruption issues, and make sure that you run your code through your debugger, too.
If you still have problems, post a test that reproduces the issue (rather than little snippets of code that do not).

Easier than using valgrind is to move the listeners->size() call right after the allocation and see if it segfaults even then. If no, move it a few lines of code lower and try again, repeat. If it segfaults, you just found the lines that cause it. Maybe you have done something with the pointer along the way and this is a method to find that piece of code.
Look at the bisection method.
May not work always, it's more of a heuristic.

vector<Listener*> listeners; might save you some problems or make the reason of the code break more evident

Related

Is it possible for a line of code that's not being called to cause a bug?

I'm currently dealing with one of the strangest bugs I have ever seen. I have this "else if" statement and inside the else-if I have a line of code that is causing a bug to happen elsewhere (my program is kind of complicated so I don't think it would help to post a short snippet of code here because it would be too difficult to explain -- so I apologize in advance if this post seems rather vague).
The issue is that the line of code that is causing the bug is not being called at all. I put a break point at the line and also put a print statement before it but the program never enters that particular "if-else" statement. The bug goes away when I comment out the line and shows up again when I uncomment it. This leads me to believe that the line must be getting called somehow but my break point and prints suggest otherwise.
Has anyone ever heard of something like this happening? Why would a line of code that is not even being called affect the rest of my program? Are there other ways to detect if the line is being called somehow besides using breakpoints and print statements?
I'm using XCode as my IDE and this is a single threaded program (so it's not some weird asynchronous bug)
PROBLEM HAS BEEN SOLVED. SEE TOP ANSWER
It actually may happen in some cases indeed and I already saw it before. If the bug is some slight buffer overflow then the presence/abasence of that line may make the compiler differently optimize the memory layout (ie. not allocate some variables or arrange them in a different way or place segments differently for example) that will by chance not trigger the problem anymore.
The same applies if the bug is a strange race condition: the lack of that line may change slightly the timings (due to differently optimized code) and make the bug come out.
Very long shot: that code may even somehow trigger a compiler bug. But this may be less the case, but it may.
So: yes it's definitely possible and I already saw it. And if something like this is happening to you and you're 100% sure your code is correct then be very careful since something quite nasty may be hiding in the code.
Not that there is enough information here to really answer this question, but perhaps I can try to provide some pointers.
Optimization. Try turning it off if it is turned on at all. When the compiler is optimizing your code, it may make different decisions when a statement is present vs. when it isn't. Whenever I am dealing with bugs that go away when a a seemingly unrelated code construct is changed, it is usually that the optimizer is doing something differently. I suppose a very simple example would be if the statement accesses something that the compiler would otherwise think is never accessed and can be folded away. The "unrelated" line may take an address of something which affects aliasing information, etc. All this isn't to say that the optimizer is wrong, your code likely still does have a bug, but it just explains the weird behaviour.
Debugging. It is very unlikely that the bug is in this line that is not reached. What I would focus on is setting watch points for the variables that are getting incorrect values (assuming you can narrow it down to what is receiving the wrong value).
These very weird issues often indicate an uninitialized variable or something along those lines. If the underlying compiler supports it, you can try providing an option that will cause the program to trap when an uninitialized memory location is being accessed.
Finally, this could be an indication that something is overwriting areas of the stack (and perhaps less likely other memory areas - heap, data). If you have anything that is writing to arrays allocated on the stack, check if you're walking past the end of the array.
Make sure you're using { and } around the bodies in your if() and else clauses. Without them it's easy to wind up with something like this:
if (a)
do_a_work();
if (b)
do_a_and_b_work();
else
do_not_a_work();
Which actually equates to this (and is not what's implied by the indenting):
if (a) {
do_a_work();
}
if (b) {
do_a_and_b_work();
} else {
do_not_a_work();
}
because the brace-less if (a) only takes the first statement below it for its body.
Commenting out your mystery line may be changing which code belongs to which if-else.

ofstream::open creates file, but then crashes (bad pointer in locale::getloc()?)

So I have some code that looks like this, written in and compiled with Visual Studio 2010:
if ( outputFile.is_open() )
{
outputFile.close();
}
if ( !outputFile.is_open() ) // condition for sanity-checking
{
outputFile.open("errorOut.txt", ios::out);
}
This crashes on an access violation. Attaching a debugger shows that the first condition is false (outputFile is not open), the second condition is true (outputFile is closed, which is good since I just checked it). Then open() gets called, and eventually locale::getloc() attempts to dereference a null pointer, but I have no idea why that would be happening (since that's now three classes deep into the Standard Library).
Interestingly, the file "errorOut.txt" does get created, even though the open call crashes.
I've spent a few hours watching this in a debugger, but I honestly have no idea what's going on. Anyone have any ideas for even trying to determine what's wrong with the code? It's entirely possible that some code elsewhere is contributing to this situation (inherited code), but there's a lot of it and I don't even know where to look. Everything up to that point seems fine.
OK, I'm not really sure if this is the best way to handle this, but since this involved some truly strange behavior (crashing in the middle of an STL function, and some other oddities like hanging on exit(1); and the like), I'll leave an explanation here for the future.
In our case, the error seemed to derive from some memory corruption going on in some truly awful code that we inherited. Cleaning up the code in general eliminated this crash and other strange behaviors displayed by the program.
I don't know if this will be useful to anyone; maybe it would have been better to simply delete the question. I'm actually somewhat curious if I should have, if anyone wants to leave a comment.

Segmentation fault - std::_Rb_tree

I'm going through some crashes in my application and would like to know if anyone can help.
gdb:
http://pastebin.com/tW6HzY2Y
What can cause this? I'm using Ubuntu 10.04.3.
Edit:
Look likes the problem is here:
bool ChatChannel::removeUser(Player* player)
{
UsersMap::iterator it = m_users.find(player->getID());
if(it == m_users.end())
return false;
m_users.erase(it);
return true;
}
This is odd, there was never any problem with this part. I do not know how to reproduce the error.
There isn't much to go from as other suggested. The stack trace you linked to has nearly no information. However, there is a tiny bit which is safe to say: based on this=0x38 you are trying to find something in an object which isn't a tree. My personal guess is that your data structure containing your std::map<unsigned int, Player> has this map after a couple of other members (which have a total size of 56 bytes) but you try to access this data structure via a NULL pointer. That is, although the segmentation fault happened in std::_Rb_tree the error isn't in the std::map implementation at all.
Run your program under valgrind. It will almost certainly spit out some error before the actual crash which may point more closely to the source of the error (as opposed to the collateral damage).
Do not know when/where the pointer to Player is initilized/discarded. I would look at it very carefully. Raw pointers are headaches most of the time.
Please look at player->getID(). Perhaps the call to member function is done at invalid memory address.

Seg fault after calling destructor successfully or calling empy destructor. C++

I am very sorry that I am not able to provide more details of my code, since I am taking over another project. The class structures are very complicated and I am unable to reproduce the issue using an easy example.
Essentally if I delete an object, all the statements in the destructor was executed successfully, but as soon as the destructor finishes execution, seg fault happens. Even if I just make the destructor empty and not do anything, the seg fault still happens. This class does not have any base class.
My code looks like this:
ParallelSynthesizer* p = new ParallelSynthesizer(argc, argv);
p->synthesize();
delete p;
cout << "after deleting" << endl;
"after deleting" was not shown, as the seg fault happens before that. But the destructor of p is executed successfully.
[EDITED AFTER SOME COMMENTS] the "synthesize()" method does use multithreading, but it is very straightforward:
pthread_t threads[num_threads];
// makes the "params" array here. skipped.
for (int i=0; i<num_threads; i++) {
pthread_create(&threads[i], NULL, synthesizeThreadMethod, (void*)(params[i]));
}
for (int i=0; i<num_threads; i++) {
pthread_join(threads[i], NULL);;
}
This pretty much all in the synthesize() method, so I don't think multithreading will result in any issue.
I am using g++ on linux. Does anybody know the possible causes of this problem?
I apologize again for not being able to find an easy example that produces this error.
One possible cause is that another object tries to access p after it got deleted.
Update You could try and run your code through valgrind. Depends a little on how well you can isolate the problem before hand. My guess so far would be that you do something bad inside your class (like constructing an object and passing p as parameter to it).
It's hard to say based on what you've said, but it sounds like you've got some heap corruption.
This kind of problem is tricky to trace and it's virtually impossible for Stack Overflow readers to fix this for you given a large code base. I would recommend running a tool like valgrind, which will track memory accesses and give you a hint at where things went wrong.
I would guess the crash happens during operator delete(void*), which is invoked by delete p; right after the destructor.
There are lots of possible causes for messing up the heap in a way that could cause a crash. A common one would be that some code previously wrote to memory before or after a new-ed object. I would run the program under valgrind memcheck; it's a very useful tool specifically for tracing down this sort of error.

What could cause a returning function to crash? C++

So I have been debugging this error for hours now. I writing a program using Ogre3d relevant only because it doesn't load symbols so it doesn't let me stack trace which made finding the location of the crash even harder. So, write before I call a specific function I print out "Starting" then I call the function and immediately after I print "Stopping". Throughout the function I print out letters A-F where F is printed right before the function returns (one line above the last '}') The weird thing is when the crash occurs it is after the 'F' is printed but there is no 'Stopping'. Does this mean that the crash is happening in between somewhere? The only thing I can think of is something going wrong during the deallocation of some of the memory allocated during the function. I've never had anything happen like this, I will keep checking to make sure it's going wrong where I think it is.
Most of the times when something weird and un-understandable happens, it's because of something else.
You could have some dangling pointers in your code (even in a place far away from that function) pointing to some random memory cells.
You might have used such dangling pointer, and it might have resulted in overwriting some memory cells you need. The result of this is that you changed the behavior of your program by changing some variable defined elsewhere, some constants, or even some code!
I'd suggest you to debug your application using some tool able to check and report erroneous memory accesses, like Valgrind.
Anyway if you are able to localize the source of your crash and to write a really small piece of code that will crash post it here -- it could be just a simple error in your function, although it sounds unlikely, from your description.
This probably means that the error is happening when the function returns and some destructor is firing. Chances are that you have some destructor trying to free memory it doesn't own, or writing off the end of some buffer in a log, etc.
Another possibility to be aware of might come up if you aren't flushing the output stream. It's possible that "Stopping" is getting printed, but is being buffered before hitting stdout. Make sure to check for this, since if that's what's going on you'll be barking up the wrong tree.
I had a similar problem, and it turned out that my function was not returning anything when the signature expected a return type of std::shared_ptr, even though I was not using the return anywhere.
The function had the following signature:
std::shared_ptr<blDataNode> blConditionBasedDataSelectionUI::selectData(std::shared_ptr<blDataNode> inputData)
{
// My error was due to the function
// not returning anything
}
I encountered the same problem and it turned out I forgot to init my vector before appending new items, which cause error when my function was comparing the vector with other list.
std::vector<cv::Point> lefteyeCV;
void Init() {
// I need to add "lefteyeCV.clear();" here!
for (int i = 0; i < 8; i++) {
lefteyeCV.push_back(cv::Point(0, 0));
}
}
// the following comparison will crash after "return 0"
// because cl_ is of size 8, but if I run "Init()" twice, lefteyeCV.size() = 16
// then the comparison is out of range.
int irisTrack(){
for (int i = 0; i < lefteyeCV.size(); i++) {
cl_[i] = cv::Point(lefteyeCV[order[i]].x - leftRect.x, lefteyeCV[order[i]].y - leftRect.y);
}
return 0;
}
What's confusing is that, I'm using Xcode and the app crash right after "return 0" with the indecipherable message "thread 13: signal SIGABRT". However, using Visual Studio instead showed me the line where index is out of range.