SFML crash when debugging, but ok on release.

Started by
12 comments, last by Meerul264 10 years, 8 months ago

Yeah, that kind of mistake occurs alot. Part of programming is learning good practices that reduces or removes those kind of mistakes.

Two solutions:

1) Don't use "magic numbers" in your code. '10' in your code doesn't mean anything, and neither does '2'. Changing them in one place requires you to remember changing them in other places (sometimes dozens). Instead, it's much better to replace magic numbers with well-named constant variables. Changing the constant's value automaticly makes all the code that uses the constant still work properly.

Example:


//The value is only set once, in a specific location.
const int PROMPTED_TEXT_COUNT = 10;

//In one location:
sf::Text promptedText[PROMPTED_TEXT_COUNT];

//In another location:
for(size_t i = 0; i <  PROMPTED_TEXT_COUNT; i++) { ... }

2) You could make it a std::vector. Or, if you're using C++11, you could make it a std::array. std::vectors keep track of their size as part of their class, and can still be accessed through the [] subscript operator during for() loops, and can also be used with vector.at(n) which double-checks that that location is valid before accessing.

Your for-loop would then look like:


//If you're using C++11's new range-for() syntax:
for(sf::Text &text : promptedText)
{
     text.setFont(font);
}

//If you're not using C++11's range-for():
for(size_t i = 0; i < promptedText.size(); i++)
{
     promptedText[i].setFont(font);
}

I'd also make sure "text.setFont(font);" and "promptedText.setFont(font);" are in different for()-loops, unless you're 100% confident that they will always forever have the same number of elements as each other.

Advertisement


//If you're not using C++11's range-for():
for(int i = 0; i < promptedText.size(); i++)
{
     promptedText[i].setFont(font);
}

You are using promptedText.size(). Doesn't that require promptedText.push_back(sf::Text &) first? Is this possible if I were to initialise the font of this text before i begin the game loop (i.e before window is open) ?

Or you are saying that I have to implement the std::vector's reserve() or resize() first?

Oh, yes, most certainly resize to the correct size first. I was (incorrectly) assuming your code was already doing that in your existing array elsewhere.

I see. Thanks again :)

This topic is closed to new replies.

Advertisement