Is this going to leak memory or is it ok? Please also let me know if there is something else that I need to pay attention to.

typedef struct 
int len;
UC * message; 

pack * prepare_packet_to_send(const int length,const unsigned char tag,const int numargs, ... )

pack *layer=  malloc(sizeof(pack));
va_list listp;
va_start( listp, numargs );
int step = 0;
layer->message = (unsigned char *) malloc(length);
layer->len = length;
int i = 0;
int len = 0;
unsigned char *source_message ; 

for( i = 0 ; i < numargs; i++ )

source_message = va_arg( listp, unsigned char *);
len = va_arg( listp, long);
memcpy(layer->message+step, source_message, (long) len);

va_end( listp );
 return layer;



pack *test = call prepare_packet_to_send(sizeof(var1)+sizeof(var2),any tag,any args) 

// are following two frees correct/enough? or is there something else i need to do to     prevent mem leak?



Yes and no.

As you've used it here, I don't see a memory leak, so that would be a "no."

The function itself, however allocates memory without ever freeing it, so it's pretty much a memory leak waiting to happen -- the client code has to free the memory it allocates. Worse, freeing that memory is slightly non-trivial (two separate frees that have to happen in the right order) so it's not just a matter of whoever uses it remembering to free the memory, but there's also a possibility of them doing it wrong even if they do remember. Granted, it's not terribly complex either, but I'd still probably add a little function like:

void destroy_sent_packet(pack *p) { 

So it's at least back to the client just remembering to free the memory.

| improve this answer | |
  • \$\begingroup\$ Thank you so much, so If I understood you correctly, as long as I use your free function after each call it won't leak? \$\endgroup\$ – user12529 Apr 11 '12 at 0:46

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy