简体   繁体   English

分段错误或可疑的指针到指针转换(面积太小)

[英]Segmentation fault or Suspicious pointer-to-pointer conversion (area too small)

long keyIntValue;
uint8_t *value; 

sscanf(buffer, " %*[^\"\n]\"%9[^;\"\n]", keyStringValue);
keyIntValue = strtol(keyStringValue, NULL, 16);
*value = *(uint8_t*)keyIntValue;
printf("The value is 0x%x \n", *value);

I get segmentation fault for the above code with GCC compiler 我在GCC编译器中遇到了以上代码的分段错误

*(long *)value = keyIntValue;
 printf("The value is 0x%x \n", *(long *)value);

The above code works with gcc and gets the correct output but I get Suspicious pointer-to-pointer conversion (area too small) with bitbake compiler 上面的代码与gcc一起使用并获得正确的输出,但是我使用bitbake编译器得到了可疑的指针到指针的转换(面积太小)

How to solve this? 如何解决呢?

*value = *(uint8_t*)keyIntValue;

取消引用未初始化的指针会导致未定义的行为,从而导致分段错误。

If you would like to treat a portion of keyIntValue as a uint8_t , you can do it by taking an address of keyIntValue , like this: 如果keyIntValue的一部分视为uint8_t ,则可以通过采用keyIntValue的地址来keyIntValue ,如下所示:

unsigned char *value;
value = (unsigned char*)(&keyIntValue);
printf("The value is 0x%x \n", *value);

Note: The reason I changed the type of value to a pointer to unsigned char is to avoid violating the strict aliasing rule. 注意:之所以将value的类型更改为指向unsigned char的指针,是为了避免违反严格的别名规则。 Pointers to character types are allowed to alias to anything, so changing the type fixes the aliasing problem. 允许将字符类型的指针用作任何别名,因此更改类型可以解决别名问题。

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

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