Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

unsafe string operation? #87

Closed
tsprinkmeier opened this issue Sep 5, 2024 · 4 comments
Closed

unsafe string operation? #87

tsprinkmeier opened this issue Sep 5, 2024 · 4 comments

Comments

@tsprinkmeier
Copy link

tsprinkmeier commented Sep 5, 2024

system(route_cmd.str().c_str());

I believe this line may be unsafe as there is no guarantee that the temporary instance of std::string (and therefore the buffer returned by the c_str() function) persists for the length of the call to system()

I propose the following change:

        // create a copy of the generated string for logging and executing
        const std::string str(route_cmd.str());
        logger::debug()
            << "session::system(" << str << ")";
        
        system(str.c_str());
@SpareSimian
Copy link

The call to system() is safe but two temporary std::strings are created, one for logging and one for invoking system(). So the proposed replacement code is slightly more efficient.

The temporary in the current call to system() lives to the end of the statement, after system() returns. So the C string will remain valid for the duration of the call.

@tsprinkmeier
Copy link
Author

tsprinkmeier commented Sep 6, 2024

The temporary in the current call to system() lives to the end of the statement,

I thought the temporary instance was only guaranteed to live long enough to call "c_str()".
It was then eligible for destruction (i.e. before the system call is invoked).
The memory it allocated (i.e. the pointer c_str() returns) is unlikely to have been reused, so the call probably works.

@DanielAdolfsson
Copy link
Owner

Temporary objects are released at the end of a full-expression- in this case after the function call.
But if you want to reuse route_cmd.str(), you can open a PR

@tsprinkmeier
Copy link
Author

I had a bug like this a LONG time ago before preserving temporary objects was a thing.
I'm glad this has been addressed and happy to have learnt something.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants