Search code examples
c++dangling-pointerraylib

C++ Dangling pointer issue


I am using the Raylib GUI framework for a project that displays all the nodes within an iteration of the Collatz Conjecture. In my program, I have a class for a Node object that acts simply as a circle with a labelled number. The variable text in my draw method, however, has an issue; C26815: The pointer is dangling because it points at a temporary instance which was destroyed. I'm new to C++ and don't have access to any books to teach me at the moment, hence I'm not entirely sure what a "dangling" pointer is or what it means, but I'm fairly certain it's the reason I can't display any text on my nodes. Here's my Node class:

class Node {
private:
    int x;
    int y;
    int value;
    int radius;
public:
    Vector2 get_pos() {
        return Vector2{ (float)x, (float)-value * 25 };
    }

    void set_radius(int newRadius) {
        radius = newRadius;
    }
    
    void set_value(int newValue) {
        value = newValue;
    }

    void set_x(int newX) {
        x = newX;
    }

    void set_y(int newY) {
        y = newY;
    }

    void draw() {
        
        if (value) {
            const char* text = std::to_string(value).c_str();
            Vector2 size = MeasureTextEx(GetFontDefault(), text, 32.0f, 0.0f);
            Vector2 pos = get_pos();
            DrawCircle(pos.x, pos.y, radius, WHITE);
            DrawText(text, pos.x - size.x / 2, pos.y - size.y / 2, 32, BLACK);
        }
    }
};

Any help or explanation as to what's going on would be appreciated.

EDIT: Other people have had similar issues on other questions but none of the answers made sense to me or felt applicable to my situation.


Solution

  • In this line

    const char* text = std::to_string(value).c_str();
    

    You are calling c_str() which returns a pointer to the buffer of the temporary returned by std::to_string(value). This temporaries lifetime ends at the end of this line. The pointer returned from c_str is only valid as long as the string is still alive.

    If DrawText copies the string (rather than just copying the pointer you pass) you can fix it via

            std::string text = std::to_string(value);
            Vector2 size = MeasureTextEx(GetFontDefault(), text, 32.0f, 0.0f);
            Vector2 pos = get_pos();
            DrawCircle(pos.x, pos.y, radius, WHITE);
            DrawText(text.c_str(), pos.x - size.x / 2, pos.y - size.y / 2, 32, BLACK);