开发者

safe casting in C

开发者 https://www.devze.com 2023-03-07 13:50 出处:网络
hello everyone I have this snippet of the code: void writer(void* param){ if(N开发者_开发百科ULL == param){

hello everyone I have this snippet of the code:

void writer(void* param){
    if(N开发者_开发百科ULL == param){
        return;
    }
    param = (param_t*)param;
...
}

is it safe code, or not, param is from type param_t*, but I'm sick doing every time casting when I use it in function, do Somebody have another elegant solution? thanks in advance


That is a strange no-op.

When you define the function you say param is of type void*.
Then, with the cast, you explicitly convert it to param_t*
And the compiler implicitly converts that param_t* to void* with the assignment.

You need another variable

void writer(void *param) {
    param_t *internal_param;

    if (NULL == param) return;
    internal_param = param;
    /* ... */
}


You do not have to cast a void* to another pointer type in C.

So just do:

void writer(void* param){
   param_t *myparam;
    if(NULL == param){
        return;
    }
    myparam = param;
...
}

(But why are you using a void* for the argument anyway?)


The (implicit) cast in the assignment is safe even if the pointer value is NULL, so there's no need to defer it. You could do this:

void writer(void* param)
{
  param_t* myparam = param;

  if (myparam == NULL)
    return;

  ...
}


The obvious solution is to avoid using void * and use param_t * instead, as in:

void writer(param_t * param)
{
  if (param == NULL)
  {
    return;
  }

  ...
}

You could drop the NULL test if you know that it's never called with a NULL pointer. Alternatively, you could replace it with assert(param != NULL).

0

精彩评论

暂无评论...
验证码 换一张
取 消