bugfix for double-freeing packets
authorBrendan Hansen <brendan.f.hansen@gmail.com>
Mon, 4 Apr 2022 23:48:46 +0000 (18:48 -0500)
committerBrendan Hansen <brendan.f.hansen@gmail.com>
Mon, 4 Apr 2022 23:48:55 +0000 (18:48 -0500)
src/packet.onyx
src/peer.onyx

index a2a7e58d5d575dfb37ed2a010c063ccee9fd5a60..8b251fccc1c6b0b5eac7b0c5eb8ad228429cd196 100644 (file)
@@ -34,6 +34,8 @@ Packet :: struct {
     // The allocator used for the data. Only used if
     // free_data is set to true.
     data_allocator := context.allocator;
+
+    reference_count := 0;
 }
 
 Acknowledgement :: struct {
index 6a2b1c49202fba5e9bd2c21f2524bf16ae42482c..c6e5128a533c35c4ef91ba16de83e16596c2a4cb 100644 (file)
@@ -84,6 +84,7 @@ peer_queue_outgoing_command :: #match {
         out := new(Outgoing_Command);
         out.command = command;
         out.packet = packet;
+        if packet != null do packet.reference_count += 1;
 
         peer_setup_outgoing_command(peer, out);
         return out;
@@ -291,11 +292,17 @@ peer_remove_sent_reliable_command :: (peer: ^Peer, seq_num: u16, channel: Channe
 }
 
 peer_free_outgoing_command :: (peer: ^Peer, command: ^Outgoing_Command) {
-    if command.packet.free_data {
-        raw_free(command.packet.data_allocator, command.packet.data.data);
-    }
+    if command.packet != null {
+        command.packet.reference_count -= 1;
+        if command.packet.reference_count <= 0 {
+            if command.packet.free_data {
+                raw_free(command.packet.data_allocator, command.packet.data.data);
+            }
 
-    if command.packet != null do cfree(command.packet);
+            cfree(command.packet);
+        }
+    }
+    
     cfree(command.command);
     cfree(command);
 }