简体   繁体   中英

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 ?

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. To do this without malloc just create a local object:

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 . If you want to use your struct as a pointer you must use either malloc or new to allocate its memory in the heap.

If you don't want to use malloc or new, you should create a local variable. 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)); 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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