0

I am trying to get a window size from a pointer on sf::RenderWindow, but when I call a method getSize() it gives me a segmentation fault:

sf::RenderWindow* winHandle;

void createHandle(sf::RenderWindow *rw, {...}){
    winHandle = rw;
}

sf::Vector2i getWindowSize() const {
    return static_cast<sf::Vector2i>(winHandle->getSize());
}

createHandle is acting like a constructor here, just sets the value of winHandle as a pointer to the RenderWindow.

Update: after some research and debugging I determined that my problem was because of winHandle beeing null, but I still can't understand why does it work like that.

Well, I have two base classes UIHandle and UIElement, UIElement inherits UIHandle and any other UI element uses UIElement and releases It's functions.

like:

class UIHandle {
   sf::RenderWindow* winHandle;
   void createHandle({...});
   {...}
};

class UIElement : public UIHandle {
   void setHandle(UIHandle handle);
   {...}
}

class anyOtherElement : public UIElement {
   {...}
}

(The releasation might be questionable) every element works the same way(which means it has the handle pointer), but for some reason not for UITitleBar

in main() firstly I create a Handle and then link this handle to every element:

sl::UIHandle testHandle;
testHandle.createHandle(&window, sf::Vector2i(0, 0), sf::Vector2f(800, 600));
testHandle.e = &e;

sl::TestButton buttonA("Test", 20, 20, 100, 20);
buttonA.setHandle(&testHandle);

sl::UIButton buttonB("Test", 60, 60, 100, 20);
buttonB.setHandle(&testHandle);

sl::UITitleBar TitleBar("Test titlebar");
TitleBar.setHandle(&testHandle);

Oh, well, even though the pointer is not null it still doesnt work as intented and causes a segfault with other UIElements.

iTs.SL4y3R
  • 74
  • 8
  • 6
    Please **[edit]** your question with an [mre] or [SSCCE (Short, Self Contained, Correct Example)](http://sscce.org) – NathanOliver Sep 24 '19 at 14:02
  • The error is most likely not in the code shown. There is nothing terribly wrong with the code here at least, that's all we can tell you. – Max Langhof Sep 24 '19 at 14:17

1 Answers1

0

My suggestion is to check whether the pointer is NULL or not before trying to access the content of the pointer. winHandle might be NULL or is not a valid pointer. It is very difficult to know the exact reason with the code you posted.

Segmentation fault happen in many cases as given below.

  1. When pointer is NULL
  2. When you try to alter the contents of readonly memory
  3. When you try to use dangling pointer

You can read more on segmentation fault using this question on stack overflow

What is a segmentation fault?

kadina
  • 5,042
  • 4
  • 42
  • 83