C++ Segmentation fault in binary_function - c++

I'm using Visual Studio 2010 Beta 2 (also tried with NetBeans), and I'm having a segmentation fault in the following code:
// One of the #link s20_3_3_comparisons comparison functors#endlink.
template <class _Tp>
struct less : public binary_function<_Tp, _Tp, bool>
{
bool
operator()(const _Tp& __x, const _Tp& __y) const
{ return __x < __y; } //this is the problem line
};
I don't know what in my program calls it, but I am trying to find out. (I think it's a map) Does anyone know what to do, or has encountered this before?

There's nothing wrong with this code; the problem lies in your code that's calling it. (In fact, since this is part of the STL, it's extremely unlikely that there's a problem with this code.) It's probably getting passed an invalid reference due to deallocated memory, a NULL pointer, or similar.
less is used, by default, for std::map, std::set, and likely some other containers that I'm not thinking of right now, so you can check if you have any containers such as those that are being left with invalid values.
(Really, though, the easiest approach is to do as James McNellis said - run it in a debugger and look at your stack trace.)

I had the same problem yesterday.
This is tried and tested code so there is a very low probability this is causing the crash.
Usually there are three possibilities for this crash:
another problem is causing a corruption of the data that this function is called on
another problem is causing a corruption of your stack causing this function to be called when it shouldn't be
any combination of the two possibilities above.
To diagnose this, run your code in the VS debugger. When your application crashes, look at the parameter values and check that the stack trace shown in the debugger is the same as the stack trace you should see (click on each entry in the stack trace and look and see the code is calling what it should).

Related

Release fails where debug doesn't

I have a problem with my code, it seems to fail in a weird way in release mode, debug mode works just fine.
I am out of ideas and clues. I would like to get a direction for what should i do.
So here is the problematic code:
static inline void FindPoint(Line *First,AABB *Second,point *Pt,int direction)
{
std::vector<point*> pntvec; ... }
When i call function FindPoint it is all fine and everything is set well.
But when i reach the vector initialization the First pointer is reset to the same address as the vector.
That causes unexpected behavior.
So i thought the problem was in the commonalities. Both Line and the vector are using the point structure.
Yet i was not able to find anything unusual.
here are the structures
typedef struct
{
double x;
double y;
}point;
typedef struct
{
double incline;
double y;
double x;
double c;
point start,finish;
}Line;
And here is the initialization of the data sent to parameter First:
Line *objvec = new Line;
so what could be the problem can any one tell?
Thank you in advance
Edit:
A better look at the code
http://pastebin.com/rki7EdM6
You're using pointers more heavily than you should for these simple types. Pointers and dynamic allocation are the likely sources of your undefined behavior. So a simple first step is to refactor and clean up your code, preferring stack variables and pass-by-reference for simple types. In all likelihood, the undefined behavior will go away, or the error will be easier to spot.
[Caveat: I can't get to pastebin, so I can't see your full code. Prefer simple examples right here on the site]
For example, your function signature should probably be this (I'm guessing about which parameter is the output)
static inline point FindPoint(const Line &First, const AABB &Second,int direction)
And
Line *objvec = new Line;
should just be
Line objvec;
etc, etc.
std::vector<point> pntvec;
is probably the most important. A vector of pointers is ok, but should be avoided if possible. One of the nice parts about standard containers is the auto-cleanup when the variable goes out of scope. You don't get that with a vector of pointers, since the vector doesn't know to call delete on every element. You have to do it yourself.
"so what could be the problem can any one tell?"
If such a situation occurs, the most probable reason is, you have hit undefined behavior in your code somewhere else.
I can't tell any more from the context and code you have posted. But using a tool like valgrind is likely to do this right on your service.

Weird Intel C++ compiler error

I'm working on this VST convolution plugin (Windows 7 64bit, VS2010) and I decided to try the Intel c++ compiler. I was in the process of optimizing the algorithm so I had a backup project in case of any screw ups and one I was doing experiments on. Both projects would compile and run with no problems. After installing the Intel compiler though the project I was experimenting on would cause a heap corruption error, so I start debugging to track down the problem but I can't find the line of code that causes it since the heap corruption error is not triggered during execution but after the termination of the DLL (there are also no access violations showed by the debugger).
At this point I start cutting out parts of the code to see if I can isolate the problem and I discover (obviously) that it was the class I was eperimenting on. Now here comes the weird part: I can change the code inside the methods but as soon as I add a variable to the backup class (the one that works fine), even an int, I get the heap corruption error, just a decleared and never referenced variable is enough.
This is the class CRTConvolver:
class CRTConvolver
{
public:
CRTConvolver();
~CRTConvolver();
bool Init(float* Imp, unsigned ImpLen, unsigned DataLen);
void doConv(float* input);
Buff Output;
int debug_test;
private:
void ZeroVars();
int Order(int sampleFrames);
template <class T> void swap ( T& a, T& b );
Buff *Ir_FFT,*Input_FFT,Output2,Tmp,Prev,Last;
float *Tail;
unsigned nBlocks,BlockLen,Bl_Indx;
IppsFFTSpec_R_32f* spec;
};
that "int debug_test;" makes the difference between a perfectly working VST module and a program that crashes on initialization from Cubase.
always for debugging purposes here are destr and constr:
CRTConvolver::CRTConvolver()
{
//IppStatus status=ippInit();
//ZeroVars();
}
CRTConvolver::~CRTConvolver()
{
//Init(NULL,NULL,NULL);
}
Here is what class Buff looks like:
class Buff {
public:
Buff();
Buff(unsigned len);
~Buff();
float* buff;
unsigned long length;
private:
void Init(unsigned long len);
void flush();
friend class CRTConvolver;
}
Buff::Buff()
{
length=NULL;
buff=NULL;
}
Buff::~Buff()
{
// flush();
}
basically this class if created and destructed does absolutely nothing, it just contains the length and buff variables. If I also bypass those two variable initializations the heap error goes away.
The software crashes on simple construction and subsequent destruction of the class CRTConvolver even though all it does is nothing, this is the part that really doesn't make sense to me...
As a side note, I create my CRTConvolver class like this:
ConvEng = new CRTConvolver[NCHANNELS];
If I declare it like this instead:
CRTConvolver ConvEng[NCHANNELS];
I get a stack corruption error around variable ConvEng.
If I switch back to Microsoft compiler the situation stays the same even when compiling and running the exact same version that could run without errors before....
I can't stress enough the fact that before installing the Intel compiler everything was running just fine, is it possible that something went wrong or there's an incompatibility somewhere ?
I'm really running out of ideas here, I hope someone will be able to help.
thanks
Going to guess, since the problem is most likely undefined behavior, but in some other place in your code:
Obey the rule of three. You should have a copy constructor and assignment operator. If you're using std containers, or making copies or assignments, without these you run into trouble if you delete memory inside the destructor.
It looks to me that the CRTConvolver default constructor (used in creating an array) is writing to memory it doesn't own. If the Intel compiler has different class layout rules (or data alignment rules), it might be unmasking a bug that was benign under the Microsoft compiler's rules.
Does the CRTConvolver class contain any instances of the Buff class?
Updated to respond to code update:
The CRTConvolver class contains four instances of Buff, so I suspect that is where the problem lies. It could be a version mismatch -- the CRTConvolver class thinks that Buff is smaller than it really is. I suggest you recompile everything and get back to us.

Remove never-run call to templated function, get allocation error on run-time

I have a piece of templated code that is never run, but is compiled. When I remove it, another part of my program breaks.
First off, I'm a bit at a loss as to how to ask this question. So I'm going to try throwing lots of information at the problem.
Ok, so, I went to completely redesign my test project for my experimental core library thingy. I use a lot of template shenanigans in the library. When I removed the "user" code, the tests gave me a memory allocation error. After quite a bit of experimenting, I narrowed it down to this bit of code (out of a couple hundred lines):
void VOODOO(components::switchBoard &board) {
board.addComponent<using_allegro::keyInputs<'w'> >();
}
Fundementally, what's weirding me out is that it appears that the act of compiling this function (and the template function it then uses, and the template functions those then use...), makes this bug not appear. This code is not being run. Similar code (the same, but for different key vals) occurs elsewhere, but is within Boost TDD code.
I realize I certainly haven't given enough information for you to solve it for me; I tried, but it more-or-less spirals into most of the code base. I think I'm most looking for "here's what the problem could be", "here's where to look", etc. There's something that's happening during compile because of this line, but I don't know enough about that step to begin looking.
Sooo, how can a (presumably) compilied, but never actually run, bit of templated code, when removed, cause another part of code to fail?
Error:
Unhandled exceptionat 0x6fe731ea (msvcr90d.dll) in Switchboard.exe:
0xC0000005: Access violation reading location 0xcdcdcdc1.
Callstack:
operator delete(void * pUser Data)
allocator< class name related to key inputs callbacks >::deallocate
vector< same class >::_Insert_n(...)
vector< " " >::insert(...)
vector<" ">::push_back(...)
It looks like maybe the vector isn't valid, because _MyFirst and similar data members are showing values of 0xcdcdcdcd in the debugger. But the vector is a member variable...
Update: The vector isn't valid because it's never made. I'm getting a channel ID value stomp, which is making me treat one type of channel as another.
Update:
Searching through with the debugger again, it appears that my method for giving each "channel" it's own, unique ID isn't giving me a unique ID:
inline static const char channel<template args>::idFunction() {
return reinterpret_cast<char>(&channel<CHANNEL_IDENTIFY>::idFunction);
};
Update2: These two are giving the same:
slaveChannel<switchboard, ALLEGRO_BITMAP*, entityInfo<ALLEGRO_BITMAP*>
slaveChannel<key<c>, char, push<char>
Sooo, having another compiled channel type changing things makes sense, because it shifts around the values of the idFunctions? But why are there two idFunctions with the same value?
you seem to be returning address of the function as a character? that looks weird. char has much smaller bit count than pointer, so it's highly possible you get same values. that could reason why changing code layout fixes/breaks your program
As a general answer (though aaa's comment alludes to this): When something like this affects whether a bug occurs, it's either because (a) you're wrong and it is being run, or (b) the way that the inclusion of that code happens to affect your code, data, and memory layout in the compiled program causes a heisenbug to change from visible to hidden.
The latter generally occurs when something involves undefined behavior. Sometimes a bogus pointer value will cause you to stomp on a bit of your code (which might or might not be important depending on the code layout), or sometimes a bogus write will stomp on a value in your data stack that might or might not be a pointer that's used later, or so forth.
As a simple example, supposing you have a stack that looks like:
float data[10];
int never_used;
int *important pointer;
And then you erroneously write
data[10] = 0;
Then, assuming that stack got allocated in linear order, you'll stomp on never_used, and the bug will be harmless. However, if you remove never_used (or change something so the compiler knows it can remove it for you -- maybe you remove a never-called function call that would use it), then it will stomp on important_pointer instead, and you'll now get a segfault when you dereference it.

accessing element of boost sparse_matrix seems to stall program

I've got a strange bug that I'm hoping a more experience programmer might have some insight into. I'm using the boost ublas sparse matrices, specifically mapped_matrix, and there is an intermittent bug that occurs eventually, but not in the initial phases of the program. This is a large program, so I cannot post all the code but the core idea is that I call a function which belongs to a particular class:
bool MyClass::get_cell(unsigned int i, unsigned int j) const
{
return c(i,j);
}
The variable c is defined as a member of the class
boost::numeric::ublas::mapped_matrix<bool> c;
When the bug occurs, the program seems to stop (but does not crash). Debugging with Eclipse, I can see that the program enters the boost mapped_matrix code and continues several levels down into std::map, std::_Rb_tree, and std::less. Also, the program occasionally traces down to std::map, std::_Rb_tree, and std::_Select1st. While code is executing and the active line what's in memory changes in _Rb_tree, execution never seems to return in the level of std::map. The line in std::map the program is stuck on is the return of the following function.
const_iterator
find(const key_type& __x) const
{ return _M_t.find(__x); }
It seems to me that there is some element in the c matrix that the program is looking for but somehow the underlying storage mechanism has "misplaced it". However, I'm not sure why or how to fix it. That could also be completely off base.
Any help you can provide would be greatly appreciated. If I have not included the right information in this question, please let me know what I'm missing. Thank you.
Some things to try to debug the code (not necessarily permanent changes):
Change the bool to an int in the matrix type for c, to see if the matrix expects numeric types.
Change the matrix type to another with a similar interface, possibly plain old matrix.
Valgrind the app (if you're on linux) to check you're not corrupting memory.
If that fails, you could try calling get_cell every time you modify the matrix to see what might be causing the problem.
Failing that, you may have to try reduce the problem to a much smaller subset of code which you can post here.
It might help if you tell us what compiler and OS you're using.
Is this part of a multithreaded program?
I ask, because usually when I see problems in STL, it ends up being a problem with unsynchronized access.

VC++ 6.0 vector access violation crash. Known bug?

I'm trying to use a std::vector<>::const_iterator and I get an 'access violation' crash. It looks like the std::vector code is crashing when it uses its own internal First_ and Last_ pointers. Presumably this is a known bug. I'm hoping someone can point me to the correct workaround. It's probably relevant that the crashing function is called from an external library?
const Thing const* AClass::findThing (const std::string& label) const
{
//ThingList_.begin() blows up at run time. Compiles fine.
for (std::vector<Thing*>::const_iterator it = ThingList_.begin(); it != ThingList_.end(); ++it) {
//Irrelevant.
}
return 0;
}
Simply calling ThingList_.size() also crashes.
This is sp6, if it matters.
If you're passing C++ objects across external library boundaries, you must ensure that all libraries are using the same runtime library (in particular, the same heap allocator). In practice, this means that all libraries must be linked to the DLL version of MSVCRT.
It's almost certainly a bug in your code and not std::vector. This code is used by way too many projects to have such an easy to repro bug.
What's likely happening is that the ThnigList_ variable has been corrupted in some way. Was the underlying array accessed directly and/or modified?
I agree with Jared that it is probably in your code,
never the less, you should be sure your stl libs are up to date.
The dinkumware site has the patched files you need.
You should update just to be safe