I am traying to code an AVL Tree class in c++ that supports the normal operations for homework.
while trying code the insert member function I found out that when I debug and put a break point in this member function the debugger goes crazy.
to make sure it is not something that I code wrong I changed the code to this simple one to see what happens:
template<class X,class Y>
void AvlTree<X,Y>::insert(const X& key,const Y& data)
{
if(this==nullptr)
{
std::cout<<"I am null"<<std::endl;
}
std::cout<<"insorted"<<std::endl;
}
It turns out that while running the program:
int main()
{
AvlTree<int,int> tree;
tree.insert(1,1);
}
the insert function prints "insorted" but while debugging the program and putting a break point on the <<"insorted"<< it prints "I am null" a lot of times. I don't really get why the this pointer is null while calling it on a non null tree.
is someone knows what seems to be the problem?
Related
I have a Function pass, called firstPass, which does some analysis and populates:
A a;
where
typedef std::map< std::string, B* > A;
class firstPass : public FunctionPass {
A a;
}
typedef std::vector< C* > D;
class B {
D d;
}
class C {
// some class packing information about basic blocks;
}
Hence I have a map of vectors traversed by std::string.
I wrote associated destructors for these classes. This pass works successfully on its own.
I have another Function pass, called secondPass, needing this structure of type A to make some transformations. I used
bool secondPass::doInitialization(Module &M) {
errs() << "now running secondPass\n";
a = getAnalysis<firstPass>().getA();
return false;
}
void secondPass::getAnalysisUsage(AnalysisUsage &AU) const {
AU.addRequired<firstPass>();
AU.setPreservesAll();
}
The whole code compiles fine, but I get a segmentation fault when printing this structure at the end of my first pass only if I call my second pass (since B* is null).
To be clear:
opt -load ./libCustomLLVMPasses.so -passA < someCode.bc
prints in doFinalization() and exits successfully
opt -load ./libCustomLLVMPasses.so -passA -passB < someCode.bc
gives a segmentation fault.
How should I wrap this data structure and pass it to the second pass without issues? I tried std::unique_ptr instead of raw ones but I couldn't make it work. I'm not sure if this is the correct approach anyway, so any help will be appreciated.
EDIT:
I solved the problem of seg. fault. It was basically me calling getAnalysis in doInitialization(). I wrote a ModulePass to combine my firstPass and secondPass whose runOnModule is shown below.
bool MPass::runOnModule(Module &M) {
for(Function& F : M) {
errs() << "F: " << F.getName() << "\n";
if(!F.getName().equals("main") && !F.isDeclaration())
getAnalysis<firstPass>(F);
}
StringRef main = StringRef("main");
A& a = getAnalysis<firstPass>(*(M.getFunction(main))).getA();
return false;
}
This also gave me to control the order of the functions processed.
Now I can get the output of a pass but cannot use it as an input to another pass. I think this shows that the passes in llvm are self-contained.
I'm not going to comment on the quality of the data structures based on their C++ merit (it's hard to comment on that just by this minimal example).
Moreover, I wouldn't use the doInitialization method, if the actual initialization is that simple, but this is a side comment too. (The doc does not mention anything explicitly about it, but if it is ran once per Module while the runOn method is ran on every Function of that module, it might be an issue).
I suspect that the main issue seems to stem from the fact A a in your firstPass is bound to the lifetime of the pass object, which is over once the pass is done. The simplest change would be to allocate that object on the heap (e.g. new) and return a pointer to it when calling getAnalysis<firstPass>().getA();.
Please note that using this approach might require manual cleanup if you decide to use a raw pointer.
Actually I am new to writing handlers but somehow i managed to write this piece of code:
#include<iostream>
using namespace std;
class test
{
public:
typedef void (test::*MsgHandler)(int handle);
test()
{
cout<<"costructor called"<<endl;
}
void Initialize()
{
add_msg_Handler(4,&test::System);
}
void System(int handle)
{
cout<<endl<<"Inside System()"<<endl;
cout<<"handle:"<<handle<<endl;
}
protected:
MsgHandler message[20];
void add_msg_Handler(int idx,MsgHandler handler)
{
cout<<endl<<"Inside add_msg_Handler()"<<endl;
cout<<"handler:"<<handler<<endl;
message[idx]=handler;
cout<<"message:"<<message[idx]<<endl;
}
};
int main()
{
test obj;
obj.Initialize();
return 0;
}
This code is working fine, I get the output as:
costructor called
Inside add_msg_Handler()
handler:1
message:1
But there are several things beyond my scope. If I am right System() should have been called in this line:
add_msg_Handler(4,&test::System);
but this is not happening. I need help on rectifying this.
Second thing is, I am not able to understand why I am getting such output:
handler:1
I mean how does handler got initialized to 1.Can somebody help me in solving this??
&test::System is not a function call, it's a pointer to the member function test::System.
(A call would look like System(0) and wouldn't compile if you used it as the parameter in question.)
If you look at the definition of add_msg_handler:
cout<<endl<<"Inside add_msg_Handler()"<<endl;
cout<<"handler:"<<handler<<endl;
message[idx]=handler;
cout<<"message:"<<message[idx]<<endl;
there's not a single place that calls the function handler.
(A call would look like (this->*handler)(0) or (this->*message[idx])(0).)
So the function isn't called because there's nothing in your code that calls it.
The output is 1 because
handler is a pointer to a member function
there's no overload of << for pointers to member functions
there is an implicit conversion from pointer to member function to bool
there's an overload of << for bool
a non-null pointer is implicitly converted to true
true outputs as 1 by default.
i got a ridiculous problem.
i have a class within inside an array member.i have a get method and a set method for the array.
the problem is that i call the set(to update) method to change the variables within the array and i see with the debugger that the variables do actually update.then when i call immediately the get method just after the set method i found the variables of the array been changed back to their ancient values.
here is the code approximately :
object.updatFunction();//sort of set method
//nothing in between
Type variable=object.getFunction();
added code:
void Cube::updtCornersNextToCentr()
{
int iHalfSide=m_SideSize/2;
int centerX(m_Center.x()),centerY(m_Center.y()),centerZ(m_Center.z());
m_CubeCornerVertices[0].setX(centerX-iHalfSide);
m_CubeCornerVertices[0].setY(centerY+iHalfSide);
m_CubeCornerVertices[0].setZ(centerZ-iHalfSide);
m_CubeCornerVertices[1].setX(centerX+iHalfSide);
m_CubeCornerVertices[1].setY(centerY+iHalfSide);
m_CubeCornerVertices[1].setZ(centerZ-iHalfSide);
//.......
m_CubeCornerVertices[7].setX(centerX+iHalfSide);
m_CubeCornerVertices[7].setY(centerY-iHalfSide);
m_CubeCornerVertices[7].setZ(centerZ+iHalfSide);
}
QVector3D * Cube::getCubeCornerVertices()const
{
static QVector3D temp[8];
for(int i=0;i<8;i++)
{
temp[i]=m_CubeCornerVertices[i];
}
return &temp[0];
}
The problem was really ridiculous, i didn’t want to let this post ambiguous.it’s a very beginner fault and it’s all about a missing « & » that caused me to update a copy.
Actually i did above simplify write the next code :
object.updatFunction();//sort of set method
//nothing in between
Type variable=object.getFunction();
And the more real code was something like:
m_WorldSpace->getCube().updtCornersNextToCentr()
//nothing in between
const QVector3D corners[8]=m_WorldSpace->getCube().getCubeCornerVertices();
all the problem was in the getCube() function which instead of being something like this :
Cube& WorldSpace::getCube()//here is the missing "&"
{
return m_Cube;
}
I wrote this
Cube WorldSpace::getCube()//this caused to get and update just a temporary copy
{
return m_Cube;
}
someone can say that i got multiple levels of getters which blinded me.
thank you.
I have a c++ program that compiles fine under gcc (4.8.1), icpc (13.1.3), clang++ (3.3) and runs okay except for the clang++ version which crashes with segfault. When I try to run this in the gdb or lldb debugger, I get EXC_BAD_ACCESS with address 0x0. The crash occurs in a member function of a helper class and the debugger claims that this has value 0x0. However going up one level, the pointer pimpl of the helper class is reported to have a non-null value and I can access its data, which look perfectly sensible.
here is some pseudo code (... is not the ellipse, but means "some parameters")
struct helper;
struct foo {
helper* pimpl;
foo(...);
void bar(...);
};
struct helper {
helper(...);
void hbar(...)
{
// crash here with *this = 0x0 according to debugger
}
};
foo::foo(...) : pimpl(new helper(...)) {}
void foo::bar(...)
{
pimpl->hbar(...); // pimpl NOT 0x0 according to debugger ??!
}
What could have gone wrong and how can I find out? Note: the question is NOT: "what is wrong with my code?"
edit 1 Perhaps it is worth mentioning that some of the arguments passed to helper::hbar() have been "optimised away by the compiler", according to the debugger, at the point of foo::bar()), while they have address 0x0 within helper::hbar()
edit 2 If I print out the value of this from within helper::hbar() the error does not occur.
edit 3 The error occurs with -O0 as well as -O2.
edit 4 The first arg of helper::hbar() was taken via const reference. If I change that to by value, everything works fine .... That argument was a spatial vector, similar to std::array<double,3>.
One way to do it - create a log file, print value of pimpl/some variable belonging to pimpl before
pimpl->hbar(...);,
and inside
pimpl->hbar(...);
Compare output from different compilers, try narrow down the problem that way adding more output to log file as you start seeing divergence...
I have been struggling with a segmentation fault for months, now I'm here to ask for help.
The segmentation fault appears when I call the following function
void foo(..., std::map<MyClass*, double> & x) {
if ( !x.empty() ) x.clear();
...
}
Class A {
private:
map<MyClass*, double> _N;
public:
void f(...) {
foo(..., _N);
...
}
};
//in main routine, the function is called in a loop
A a;
while(...) {
a.f(...);
}
Using gdb, I tacked the error to the line calling the clear() function, it shows "double free or corruption" error, and the program aborts at calling c++/4.1.2/ext/new_allocator.h:94 delete(__P) which further calls free() from the gnu library /lib64/libc.so.6. But since the elements in the map are not allocated by new, why it still calls free() to clear it up. I would really appreciate your comments. Thank you.
Given that the map is owned by another object it suspiciously sounds that the map-owning object was already deleted when the clear was called.
Also note that names starting with underscore and a capital letter are reserved for the implementation - you aren't allowed to use them.
The code looks fine to me. At least with the limited context you have provided. Usually when I run into issues like this I will simply run the valgrind memcheck tool to find the place were the first "delete" happened. Once you know that, these issues can be pretty simple to solve.