www.digitalmars.com         C & C++   DMDScript  

digitalmars.D.learn - Freeing ENetPacket

reply Kyle <smish smish.smish> writes:
Hi,

I have a function using the derelict-enet library:

void sendUbytes(ENetPeer* dest, ref ubyte[] data)
{
     //create packet
     ENetPacket* packet = enet_packet_create(cast(ubyte*)data, 
data.length * ubyte.sizeof, ENET_PACKET_FLAG_RELIABLE);

     //send packet to peer over channel id 0
     enet_peer_send(dest, 0, packet);

     //destroy packet
     enet_packet_destroy(packet);
}

If I comment out the last part (enet_packet_destroy()) the 
program eventually consumes all my RAM. If I do not, I get 
occasional segfaults. Please help. Thanks.
Nov 28 2015
parent reply Adam D. Ruppe <destructionator gmail.com> writes:
On Sunday, 29 November 2015 at 01:30:14 UTC, Kyle wrote:
 void sendUbytes(ENetPeer* dest, ref ubyte[] data)
 {
     //create packet
     ENetPacket* packet = enet_packet_create(cast(ubyte*)data, 
 data.length * ubyte.sizeof, ENET_PACKET_FLAG_RELIABLE);
So I'm not familiar with this library, but a note on D: it is usually a mistake to pass "ref something[]". The ref is unnecessary. I would also recommend against using `cast(ubyte*)data`. Instead, use `data.ptr`.
     //send packet to peer over channel id 0
     enet_peer_send(dest, 0, packet);

     //destroy packet
     enet_packet_destroy(packet);
 }

 If I comment out the last part (enet_packet_destroy()) the 
 program eventually consumes all my RAM. If I do not, I get 
 occasional segfaults. Please help. Thanks.
The tutorial says that after you send it, you should not destroy it - the library will do that for you. http://enet.bespin.org/Tutorial.html#SendingPacket "Once the packet is handed over to ENet with enet_peer_send(), ENet will handle its deallocation and enet_packet_destroy() should not be used upon it." So you definitely don't want to destroy. Are you sure the memory leak is in here? Maybe it is crashing before you can see it use all the memory with this line there. Are you compiling it as a 64 bit or a 32 bit program?
Nov 28 2015
parent Kyle <smish smish.smish> writes:
On Sunday, 29 November 2015 at 01:57:25 UTC, Adam D. Ruppe wrote:
..
 Are you compiling it as a 64 bit or a 32 bit program?
64 bit. You're probably right, I will take out the explicit destroy and look for a memory leak elsewhere, and adjust for your other suggestions. Thanks for the advice!
Nov 28 2015