我试图理解以下代码中的按位操作,但它会导致分段错误
#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
# ./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;
有人能否解释我做错了导致分段错误的原因?
答案 0 :(得分:7)
问题不在于转变,而是您没有为opt
分配内存。
解决此问题的一种方法如下:
uint8_t opt[2];