sizeof(*test_buff)
is computed at compile time and will evaluate to the size of a single element of test_buff
. As test_buff
is a buffer of char
's, that element size is guaranteed to be 1.
If I have to choose between the two options that you give, then only option 2 has useful behaviour.
On the other hand, if there comes a time that you need to change the size of your buffer, then you have to make that change in 3 (or 4 or 5) places and you have to look out for the places where the number 512 is used with a different meaning. For this reason, my preferred way of writing the code is like this:
#define BUFFER_SIZE 512
char *test_buff = (char *) malloc(BUFFER_SIZE); //allocate 512 bytes in heap memory.
bzero(test_buff, BUFFER_SIZE); //Reset buffer instead of Junk/garbage.
/* random code here to fill-in the buffer called "test_buff"...*/
...
/* Send data to another host/system [this doesn't matter though]
* using buffer "test_buff".
*/
sendto(sock_descriptor, test_buff /*buffer to send data*/, BUFFER_SIZE /* actual malloced size*/ ,...,...); // option-2a
If you want to send only the used portion of the buffer, you either need to keep explicitly track of that, or if your buffer only holds a single string, you can use strlen(test_buff)+1
(+1 to ensure the terminating '\0'
is also transmitted).
The methods I've seen most are 2 and 3.
The user supplied buffer is actually quite simple to use:
char[128] buffer;
mytype_to_string(mt, buffer, 128);
Though most implementations will return the amount of buffer used.
Option 2 will be slower and is dangerous when using dynamically linked libraries where they may use different runtimes (and different heaps). So you can't free what has been malloced in another library. This then requires a free_string(char*)
function to deal with it.
Best Answer
I think the best API for such case is to create a buffer specification and deal with it, like:
With such API, you'll avoid 1) long and cumbersome argument lists, 2) chance to mistake length for size and vice versa, and will gain instead understanding of object-like gist of your buffers.