簡體   English   中英

具有結構和memcpy的C ++分段錯誤

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM