[英]C++ Segmentation Fault with structs and memcpy
嗨,我正在尝试执行此操作..并且我遇到了段错误,mi老师不要让我使用malloc,是否可以在没有malloc的情况下执行此操作?
typedef unsigned char IPAddress[4];
typedef unsigned char MACAddress[6];
struct ethernet_frame {
MACAddress host;
MACAddress me;
uint16_t type ;
unsigned char payload[1500];
} __attribute__((__packed__));
struct ethernet_frame frame;
int send_to_ip(IPAddress ip, void *data) {
struct ethernet_frame *packet = NULL ;
MACAddress mymac = { 0 };
get_my_mac_address(mymac); // this funcions is fine, and returns void
// this is the line that causes segmentation fault
memcpy(packet->me, mymac, sizeof(mymac));
/ ... implementation continue .../
packet
指向NULL
,因此对其取消引用会导致未定义的行为,在这种情况下为分段错误。 要在没有malloc
情况下执行此操作,只需创建一个本地对象:
struct ethernet_frame packet;
MACAddress mymac = { 0 };
get_my_mac_address(&mymac);
memcpy(&packet.me, &mymac, sizeof(mymac));
请注意,我还在函数调用中添加了&
。 它返回变量的地址,从而使您可以将指针传递给本地对象。
我认为问题出在这里: packet->me
因为您正尝试引用未初始化的指针: packet
。 如果要将结构用作指针,则必须使用malloc或new在堆中分配其内存。
如果您不想使用malloc或new,则应创建一个局部变量。 尝试这个:
int send_to_ip(IPAddress ip, void *data) {
struct ethernet_frame packet;
MACAddress mymac = { 0 };
get_my_mac_address(mymac); // this funcions is fine, and returns void
// this is the line that causes segmentation fault
memcpy(packet.me, mymac, sizeof(mymac));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.