简体   繁体   English

具有结构和memcpy的C ++分段错误

[英]C++ Segmentation Fault with structs and memcpy

Hi i am trying to do this .. and i have a segmentation fault, mi teacher don't let me use malloc, is possible to do this without malloc ? 嗨,我正在尝试执行此操作..并且我遇到了段错误,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 points to NULL and thus dereferencing it causes Undefined Behaviour, in this case a segmentation fault. packet指向NULL ,因此对其取消引用会导致未定义的行为,在这种情况下为分段错误。 To do this without malloc just create a local object: 要在没有malloc情况下执行此操作,只需创建一个本地对象:

struct ethernet_frame packet;
MACAddress mymac = { 0 }; 
get_my_mac_address(&mymac);
memcpy(&packet.me, &mymac, sizeof(mymac)); 

Note that I also added & to the function calls. 请注意,我还在函数调用中添加了& Which returns the address of the variable and thus allows you to pass a pointer to a local object. 它返回变量的地址,从而使您可以将指针传递给本地对象。

I think that the problem is here: packet->me since you are trying to refer to an uninitialized pointer: packet . 我认为问题出在这里: packet->me因为您正尝试引用未初始化的指针: packet If you want to use your struct as a pointer you must use either malloc or new to allocate its memory in the heap. 如果要将结构用作指针,则必须使用malloc或new在堆中分配其内存。

If you don't want to use malloc or new, you should create a local variable. 如果您不想使用malloc或new,则应创建一个局部变量。 Try this: 尝试这个:

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.

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