this
this

Reputation: 5290

CreateProcess and lpCommandLine lifetime

I allocate memory for the parameter lpCommandLine in CreateProcess function, either with malloc or on the stack.

Can I free/release that memory immediately after the call, or do I have to wait until the process finishes?

Upvotes: 3

Views: 157

Answers (1)

David Heffernan
David Heffernan

Reputation: 612954

The buffer referred to by lpCommandLine needs be valid only for the duration of the call to CreateProcess. Once CreateProcess returns, it will not refer to that buffer again.

Imagine if you did have to keep that buffer alive. Were that the case, then all parent processes would have to outlive all of their children. That's clearly a ridiculous proposition and I'm sure you will know from experience that there is not such requirement.

There is a general principle here. By and large, API functions will not refer to their arguments after the function returns. If they do need to do so, then it will be explicitly called out in the documentation, or it will be blatantly obvious from the intent of the function. As an example of the latter I am thinking of passing a window procedure to RegisterClass. It is quite clear that the window procedure must remain valid for as long as there exists a window of that class.

Upvotes: 4

Related Questions