简体   繁体   中英

void pointer typecasting to pid_t incorrectly

I am having an issue with passing a pid_t by reference as a void pointer, and typecasting it back to a pid_t. My code is as follows:

typedef void * ProcessHandle_t;

void createProcess( ProcessHandle_t * processHandle )
{
    pid_t newTask = fork();

    if( newTask != 0 )
    {
        /* Parent process */
        /* Return a process handle for the main task to use */
        *processHandle = &newTask;
        printf("pid_t output 1: %d\n", *((pid_t *)*processHandle));
    } else
    {
        while(1){
            printf("Child running\n");
        }
    }

}

void deleteProcess( ProcessHandle_t processHandle )
{
    pid_t deleteTask = *((pid_t *)processHandle);

    printf("pid_t output 3: %d\n", deleteTask));

    kill(deleteTask, SIGKILL);
}

int main( )
{
    ProcessHandle_t processHandle;

    createProcess( &processHandle );

    printf("pid_t output 2: %d\n", ((pid_t *)*processHandle));

    deleteProcess( processHandle );

    printf("Parent exiting\n");

}

And my output is:

pid_t output 1: 19876
pid_t output 2: 19876
pid_t output 3: 493972479
Parent exiting

But I have no idea why. If I do the same kind of dereferencing with ints, it works, but I get a really strange value when I do the same for pid_t.

Is there a specific reason why this does not work with pid_t, but works with other variable types?

Remember that local variables go out of scope once the function they were defined in returns.

In the createProcess function you have

*processHandle = &newTask;

Here you make *processHandle point to the local variable newTask .

When createProcess have returned, the memory previously occupied by the newTask variable no longer "exist" (actually it will be reused by the next function call), leaving you with a stray pointer.

Dereferencing this pointer will lead to undefined behavior !

If you want to copy the contents of newTask using pointers, then you need to allocate memory for the copied value, and actually copy the value into the newly allocated memory. And if you allocate memory then you of course have to free it as well.

A simpler solution is to not use pointers at all. Avoiding pointers is usually a very good way to avoid undefined behaviors and crashes in general.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM