我试图理解下面的代码中的按位运算,但是会导致分段错误

#include <stdio.h>
#include <stdint.h>

 main()
 {
     uint16_t newmss = 1024;
     uint8_t  *opt;
     unsigned int i = 0;

     opt[i] = (newmss & 0xff00) >> 8;
     opt[i+1] = newmss & 0x00ff;

     fprintf(stderr, "opt[0] is %d", opt[0]);
     fprintf(stderr, "opt[1] is %d", opt[1]);

 }

gcc -g -o shift shift.c编译

然后执行移位,我得到了细分错误
# ./shift
Segmentation fault

using gdb to debug

(gdb) run
Starting program: /home/vincent/shift

root@vincent-desktop:/home/vincent# gdb shift
GNU gdb (GDB) 7.1-ubuntu

(gdb) run
Starting program: /home/vincent/shift

Program received signal SIGSEGV, Segmentation fault.
0x0804843f in main () at shift.c:11
11      opt[i] = (newmss & 0xff00) >> 8;

有人能说明我做错了什么导致细分错误吗?

最佳答案

问题不是转移,而是您没有为opt分配内存。

解决此问题的一种方法如下:

 uint8_t  opt[2];

关于c - 按位操作导致段错误,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/16992186/

10-11 20:40
查看更多