Welcome, Guest. Please login or register. Did you miss your activation email?

Author Topic: [SOLVED] segfault displaying dynamic array rectangle  (Read 3692 times)

0 Members and 1 Guest are viewing this topic.

MrKeviscool

  • Newbie
  • *
  • Posts: 2
    • View Profile
[SOLVED] segfault displaying dynamic array rectangle
« on: July 10, 2024, 01:46:51 pm »
Hi all,
probably a silly mistake on my behalf but i cant figure out for the life of me why this program can successfully display the dimensions of the rectangle but cant actually draw it without a seg-fault. (i know the window will disappear instantly)

i know i can use other data-types but i would preferably like to allocate arrays myself.

any help would be greatly appreciated.





#include <iostream>
#include <SFML/Graphics.hpp>

sf::RenderWindow window(sf::VideoMode(1920, 1080), "window", sf::Style::Fullscreen);


int main(){
    sf::RectangleShape** recarr = (sf::RectangleShape **)malloc(sizeof(sf::RectangleShape *));
    recarr[0] = (sf::RectangleShape *)malloc(sizeof(sf::RectangleShape));
    recarr[0][0] = sf::RectangleShape(sf::Vector2f(30, 100));
    window.clear();
    std::cout << "width of block: " << recarr[0][0].getSize().x << " bytes: " << sizeof(sf::RectangleShape) << std::endl; //this works
    window.draw(recarr[0][0]); //this doesn't
    window.display(); //this works
}


returns:

width of block: 30 bytes: 344
[1]    40165 segmentation fault  ./t

window.draw(sf::RectangleShape(sf::Vector2f( 100, 30)));

(also just doing window.draw(sf::RectangleShape(sf::Vector2f( 100, 30))) works if that changes anything)

i appreciate it :D
« Last Edit: July 10, 2024, 03:55:40 pm by MrKeviscool »

Mario

  • SFML Team
  • Hero Member
  • *****
  • Posts: 879
    • View Profile
Re: segfault displaying dynamic array rectangle
« Reply #1 on: July 10, 2024, 03:01:13 pm »
You're using C++ classes like C structs, which might work or might crash and burn horrible (in undefined behavior as you're experiencing here).

In short, C++ classes should always be constructed with "new", unless you can't do so and you know what you're doing. If you use the "new" operator, memory is allocated and the class's constructor is called.

Your example snippet does not call the constructor, so you have the memory and copy some values, but something might be uninitialized or off (the actual vertex data).

Your second example that works actually does call the constructor, so there's no issue.

If you want to use SFML in a C fashion (.e.g with mallic), you should use CSFML instead.

MrKeviscool

  • Newbie
  • *
  • Posts: 2
    • View Profile
Re: segfault displaying dynamic array rectangle
« Reply #2 on: July 10, 2024, 03:55:10 pm »
it works! thanks so much :D