Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regarding dereferencing 'void *' pointer

I am not able to find out how to remove the above warning from the below line of code. data is is void pointer and as part of callback function will be receiving string in the data pointer. As I have typecast the void pointer but compiler still showing the warning.

There are basically two warnings showing up on the below line. 1. dereferencing 'void *' pointer 2. taking address of expression of type 'void

 service_ind = atoi((const char*)&data[at_response.param[0].start_of_value_index]) ? TRUE:FALSE ;

Below are required information

void * data;
AT_PARSER_RESPONSE at_response;

typedef struct
{

/*Other parameters */

AT_PARAM  param[AT_MAX_NUM_PARAM];

}AT_PARSER_RESPONSE
like image 337
Abhi Avatar asked Jan 19 '26 17:01

Abhi


1 Answers

Quoting C11, chapter §6.5.3.2:

The unary * operator denotes indirection. If the operand points to a function, the result is a function designator; if it points to an object, the result is an lvalue designating the object. If the operand has type ‘‘pointer to type’’, the result has type ‘‘type’’. If an invalid value has been assigned to the pointer, the behavior of the unary * operator is undefined.

So, your code causes undefined behavior.

Also, related, from chapter §6.2.5:

The void type comprises an empty set of values; it is an incomplete object type that cannot be completed.

So, a pointer to void is an invalid operand for dereference.


One probable practical case and the possible solution

Sometimes, for making generics, we cast a certain pointer to void *, pass that as argument to a function and then, inside a function we cast it back to the original type, based on some known information. This is, as per chapter §6.3.2.3, perfectly valid:

[...] A pointer to any object type may be converted to a pointer to void and back again; the result shall compare equal to the original pointer.

If this is your case, and you're dereferencing inside the function, you can cast the pointer to either

  • its original type (or a compatible type)
  • or a char * (see this answer for why char * is allowed)

before dereferencing.

like image 159
Sourav Ghosh Avatar answered Jan 21 '26 07:01

Sourav Ghosh



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!