coredump
coredump

Reputation: 3107

Windows API STARTUPINFO destroyed?

After creating a process and waiting for it to finish, does it's STARTUPINFO still available or is it destroyed ?

STARTUPINFO si;

bRes = CreateProcess(NULL, command, NULL, NULL, TRUE, 0, NULL, NULL, &si, &pi);

dwRes = WaitForSingleObject(pi.hProcess, INFINITE);

After this does the si gets modified/destroyed or is it left intact ?

Upvotes: 2

Views: 525

Answers (3)

himself
himself

Reputation: 4884

If you declare it like you did

STARTUPINFO si;

Then it's destroyed by C when the part of the program where it was declared finishes (it's called "going out of scope"). For instance:

void myfunct() {
  STARTUPINFO si1;
  if (condition) {
    STARTUPINFO si2;
    //...
  } //si2 destroyed here
  //...
} //si1 destroyed here

Even if CreateProcess() function wanted to preserve si1 or si2, it couldn't. Because no matter what you do, they'll be destroyed at those points.

Now, if you created si like this:

STARTUPINFO *si = malloc(sizeof(STARTUPINFO));

Then it would have been destroyed only when you explicitly called

free(si);

Some API functions require you to give them something they can keep. For those functions you must allocate parameters in a second, or even more complicated ways, and they'll tell you in the documentation when exactly you'll have to destroy it later.

But most API functions just copy whatever you pass to them and leave the source be, so it's okay to pass pointers to structures declared in a first way.

Note that in general it's not okay to "pass something to API and rely on API destroying it". Your application and API functions you call most likely use different memory managers. What has been allocated in one cannot be freed in another.

So most of the times such API will want you to either allocate data by calling some specific function, or (more common) just delete your data by yourself, later.

MYPARAM *p = malloc(sizeof(MYPARAM));
APIOpen(p);
//...much later
APIClose(p);
//It's now safe to free p
free(p);

Upvotes: 0

David Heffernan
David Heffernan

Reputation: 612954

Windows creates a copy of the startup info struct for the new process. That has to happen because the new process has a brand new address space and cannot see your struct.

Now, what happens to your struct? Well, the documentation has the answer. The parameter is annotated like this:

_In_ LPSTARTUPINFO lpStartupInfo

The _In_ means that the contents of the struct are not modified by the call to CreateProcess. So, you can be confident that when CreateProcess returns, the startup info struct has not been modified.

Upvotes: 2

Zacrath
Zacrath

Reputation: 556

The copy of the STARTUPINFO that Windows creates is destroyed. But the structure that you supply to the CreateProcess function still exists.

Upvotes: 0

Related Questions