简体   繁体   English

无效指针类型转换为pid_t错误

[英]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. 我在通过引用将pid_t作为void指针传递并将其类型转换回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. 如果我对int进行相同类型的取消引用,则可以使用,但是当我对pid_t进行相同的处理时,会得到一个非常奇怪的值。

Is there a specific reason why this does not work with pid_t, but works with other variable types? 是否有特定的原因为什么该方法不适用于pid_t,但适用于其他变量类型?

Remember that local variables go out of scope once the function they were defined in returns. 请记住,一旦在函数中定义了局部变量,它们就会超出范围。

In the createProcess function you have createProcess函数中,

*processHandle = &newTask;

Here you make *processHandle point to the local variable newTask . 在这里,使*processHandle指向局部变量 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. 返回createProcess后,先前由newTask变量占用的内存不再“存在”(实际上,它将在下一个函数调用中重新使用),从而使您留下了流浪指针。

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. 如果要使用指针复制newTask的内容,则需要为复制的值分配内存,然后将值实际复制到新分配的内存中。 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. 通常,避免使用指针是避免未定义行为和崩溃的一种很好的方法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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