1
\$\begingroup\$

I am using GLFW for a game, and I have a function which allows me to set the window title.

    // PROBLEM WITH INCREASING MEMORY USAGE
    void WindowSystem::setTitle( const string & title )
    {

        glfwSetWindowTitle( window, title.c_str() );

    }

This function is called once during every iteration of the main program loop, so that I can have a basic FPS counter. Under Xcode the program memory usage increases faster and faster. If I replace title.c_str() with a literal, the problem does not happen, i.e., the following does not cause the same memory usage growth.

        // DOESN'T CAUSE PROBLEM
        void WindowSystem::setTitle( const string & title )
        {

            glfwSetWindowTitle( window, "Hello world!" );

        }

This where the function is called.

    int SystemControl::update()
    {
        double time = glfwGetTime();
        double timeStep = time - control->lastUpdate;
        control->lastUpdate = time;

        float frameRate = 1.0f / timeStep;

        string windowTitle = std::to_string( frameRate );

        control->windowSystem->setTitle( windowTitle );

        control->physicsSystem->update( timeStep );

        return OK;
    }

The string title is allocated on the stack, and should be freed at the end of update. Could there possibly be a memory leak? I understand that the pointer for c_str() is internally managed, and does not need to be freed.

\$\endgroup\$
6
  • \$\begingroup\$ Could it be that the string literal allows compiler optimization, but the string that I am passing to the function never returns memory back to the OS? Another note: this makes initially about a 10 Mb difference, from 37 Mb, in program footprint, then it rapidly goes off past 200 Mb in about 2 minutes. \$\endgroup\$ Mar 4 '16 at 7:20
  • \$\begingroup\$ and if you pass the string as a const ref? \$\endgroup\$ Mar 4 '16 at 9:04
  • \$\begingroup\$ Note that title.c_str() could be invalid (dangling pointer) when you release title. (cplusplus.com/reference/string/string/c_str or cplusplus.com/forum/general/29153 for more detail) \$\endgroup\$
    – Niels
    Mar 4 '16 at 10:15
  • \$\begingroup\$ By the way, if working in visual studio, have a look at msdn.microsoft.com/en-us/library/x98tx3cf.aspx for tracking memory leaks \$\endgroup\$
    – Niels
    Mar 4 '16 at 10:18
  • \$\begingroup\$ Consider looking at the source and/or reporting an issue with the library. \$\endgroup\$ Mar 4 '16 at 11:15

Browse other questions tagged or ask your own question.