1

I am trying to use OGDF C++ library for a project and want to use a protected member function of a class of this library. As can't access protected members directly outside class or derived class; to use protected method of Balloon Layout class I created a class A which inherit BallonLayout class and from A protected function of super class is called in a public function "abc()" of class A; so that I can use abc() outside the class and indirectly protected function of class BallonLayout.

Here posting the code please tell me where is problem in it.

#include <ogdf/basic/Graph.h>
#include <ogdf/basic/graph_generators.h>
#include <ogdf/misclayout/BalloonLayout.h>

using namespace ogdf;

class OGDF_EXPORT A : public BalloonLayout{
        public:
            void abc(const Graph &G){
            selectRoot(G);                
            }
};

int main()
{
    int n = 5, m = 7;
    Graph G;
    ogdf::planarBiconnectedGraph(G, n, m);

    A* a;
    a->abc(G);
    cout << "Done!!";
return 0;
}

It compiles without any error but at run time it gives "Segmentation fault (core dumped)". This error comes when we try to access something(object/variable) which is not in memory. But not getting what mistake have I done.

Kara
  • 6,115
  • 16
  • 50
  • 57
Shaifali
  • 309
  • 3
  • 9

1 Answers1

0

Your code:

A* a;
a->abc(G);

doesn't initialize the pointer a. Dereferencing a null or uninitialized pointer, with either the * or -> operator, is undefined behavior.

Turns out, you don't need the pointer at all, just use:

A a;
a.abc(G);

And if you need dynamically allocated memory, include <memory> and do:

std::unique_ptr<A> a = new A(...);
a->abc(G);

For the love of life, the universe and everything, don't use naked pointers when you can.

Shoe
  • 74,840
  • 36
  • 166
  • 272