简体   繁体   English

取消引用空指针

[英]Dereferencing a void pointer

I have the below code: 我有以下代码:

#include <inttypes.h>
#include <stdlib.h>
struct a
{
  void *p;
};

int main(void)
{
  struct a *ptr = malloc(sizeof(struct a));
  ptr->p = malloc(sizeof(uint8_t));
  *((uint8_t *) ptr->p) = 2;
  return 0;
}

I am casting the void pointer before dereferencing to avoid the warning 我在取消引用之前强制转换void指针以避免警告

warning: dereferencing 'void *' pointer 警告:取消引用“ void *”指针

Am I breaking any rule by doing this or is this code good? 我是在违反规则吗,还是这段代码不错?

是的,此代码是合法的,不会引起未定义的行为(除非malloc返回NULL )。

As per the standard mandates, this code looks ok. 按照标准要求,此代码看起来不错。 a pointer to a character type can be used to point to the object without breaking the aliasing rule. 指向字符类型的指针可用于指向对象而不会违反别名规则。

To quote the standard, chapter §6.3.2.3 要引用该标准,请参见第6.3.2.3章

[...]. [...]。 When a pointer to an object is converted to a pointer to a character type, the result points to the lowest addressed byte of the object. 当指向对象的指针转换为指向字符类型的指针时,结果指向该对象的最低寻址字节。 Successive increments of the result, up to the size of the object, yield pointers to the remaining bytes of the object. 结果的连续递增(直到对象的大小)会产生指向对象剩余字节的指针。

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

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