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.
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.
You can read more on segmentation fault using this question on stack overflow