Reputation: 185
Is this correct, is it gonna leak memory in C?
unsigned char * prep( int length,int args, ... )
{
unsigned char *message = (unsigned char *) malloc(length );
va_list listp;
va_start( listp, args );
int i = 0;
int len = 0;
unsigned char *source_message ;
int step = 0;
for( i = 0 ; i < args; i++ )
{
source_message = va_arg( listp, unsigned char *);
len = va_arg( listp, long);
memcpy(message+step, source_message, (long) len);
step+=len;
}
va_end( listp );
return message;
}
than call it and free the pointer outside
unsigned char *mess = prepare_packet_to_send(some vars here);
free(*mess);
Upvotes: 0
Views: 4065
Reputation: 7630
It is fine, sometimes you have to do that, the C function strdup() does the same, you just have to follow the convention to free it after use. But I saw a bigger issue in you code, you actually allow more data to be written than the size you allocated. This is an attempt to correct this:
unsigned char * prep( int length,int args, ... )
{
int i = 0;
int len = 0;
unsigned char *source_message ;
int step = 0;
unsigned char *message = (unsigned char *) malloc(length);
va_list listp;
va_start( listp, args );
for(i = 0 ; i < args && step <= length; i++ ) {
source_message = va_arg( listp, unsigned char *);
len = va_arg( listp, long);
memcpy(message+step,source_message,(step+len >length)?length-step:len);
step+=len;
}
va_end( listp );
return message;
}
use it like.
char * p = prep(size,2,"message 1",9,"message 2",9);
if (p) {
.... work with p....
free(p);
}
Upvotes: 0
Reputation: 9661
You will use your own function like this:
unsigned char *p = prep(100, 1, "hello", 3);
// ...
free(p);
and then you'll have no memory leaks.
Upvotes: 1
Reputation: 55405
This is perfectly legal. Functions may return memory that is intended to be freed elsewhere. In fact, the malloc function you use has this exact contractual behavior.
I haven't carefully stepped through your code to verify there are no other issues, but returning malloc'd memory is definitely not an issue.
Upvotes: 2
Reputation: 55543
That's correct, it will leak memory. As long as you remember to free the return value of that function, you should be fine, however.
Upvotes: 2