wild pointer problem

wild pointer problem

Recently, I was looking at the previous code, and I have some new understanding of the previous bug. I will summarize it here, and I will share it with you.

The first is to use a send function

static int send_fun(uint16_t length, uint8_t *data);

It is necessary to judge the sent data data according to different conditions. The
following implementation is wrong

int judge_send_fun(void)
{
    int ret;
    uint8_t *data;
    if(XXX)
    {
        *data = 0;
        ret = send_fun(1, data);
    }
    else if(XXX)
    {
        *data = 1;
        ret = send_fun(1, data);
    }
    return ret;
}

The reason for the error is that the uint8_t *data set in the function is a wild pointer. Before the function calls the send_fun function, the local variables and static variables of the judge_send_fun function, the program location to jump back to, and the parameters of send_fun are pushed onto the stack (the function The implementation of the call can be seen in the process section in "In-depth Understanding of Computer Systems"). Here, the stack is just an address where data is stored. When the address of data is passed as a parameter to send_fun, only the pointer to the stack is passed. The pointer of data, in fact, because data does not point to a specific memory space (wild pointer) when it is declared, the content of data is an unreliable value, and when the send_fun function searches for a specific value according to the address of the incoming data, it gets The value is a random number, causing the program to run incorrectly.

The correct way is as follows:

int judge_send_fun(void)
{
    int ret;
    uint8_t data;
    if(XXX)
    {
        data = 0;
        ret = send_fun(1, &data);
    }
    else if(XXX)
    {
        data = 1;
        ret = send_fun(1, &data);
    }
    return ret;
}

In this way, before calling send_fun, the value of data and the parameter &data of send_fun are pushed onto the stack. At this time, the address pointed to by &data is the value of data that is pushed onto the stack, and there will be no problem that the value of data is randomly tampered with.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325589126&siteId=291194637