unsigned char* - arguments or return pointers

Hi all,
could you please tell me if it's better return a pointer or passing the pointer as an argument?


EXAMPLE ONE:

unsigned char* process(int& ln)
{
..
//only at this time I know the number of bytes to allocate. Ex 5 bytes

unsigned char* buffer = new unsigned char[5];
memcpy(...,buffer,5);

*ln=5;


return buffer;

}

from the calling method:

int l=0;
unsigned char* mybuffer = process(&l);

//using mybuffer...

delete[] mybuffer;




----------------------------------------------

EXAMPLE TWO:


int process(unsigned char* buffer)
{
..
//only at this time I know the number of bytes to copy. Ex 5 bytes


memcpy(...,buffer,5);

return 5;
}

With this second example I have to passing a unsigned char* with a fixed size:
This unsigned char may be not equal to real size required to store the buffer's size at the runtime time.

Ex.
unisgned char mybuf[20]; // oversized :)
int len = process(mybuf);

I must use only unisgned char* and not others!
So what's the better and safe solution?

many thanks
hts

Last edited on
In general there is no answer what is better. Without other code that is, more precisely without whole project design it is difficult to say what will be better.
For example, the first function design could be used as some more general wrapper for new. The second function design could be used as general initializer of your data structures.
Only I do not understand if in the second function you already know how many characters will be used then why do you return number of characters?

Hi Vlad!
thanks for your reply.

Only at the runtime time I know how many bytes I have to allocate.
Actually I use the first method but It's correct allocate memory inside a method and deallocate it outside?
> it's better return a pointer or passing the pointer as an argument?

Neither is a very good option. Consider using a vector<> instead:

1
2
3
4
5
6
7
std::vector<unsigned char> process() 
{
    //only at this time I know the number of bytes to allocate.  Ex 5 bytes
    std::vector<unsigned char> buffer(5) ;
    // ...
    return buffer ;
}

from the calling method:
1
2
3
4
std::vector<unsigned char> buffer = process() ; 
unsigned char* mybuffer = &buffer.front() ; // if required, preferably use the vector directly
// using mybuffer... 
// destructor of buffer will release the memory 

Many thanks for your suggestion.
I try!

Topic archived. No new replies allowed.