Which is better: for valid buffer length

bufferscmalloc

This is a basic question. But, I think understanding this would be helpful to play with buffers in 'C'. Thanks.

Scenario

Just a sample snippet

char *test_buff = (char *) malloc(512); //allocate 512 bytes in heap memory.
bzero(test_buff, 512); //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*/, sizeof(*test_buff) ,...,...);  // option-1
/* OR */
 sendto(sock_descriptor, test_buff /*buffer to send data*/, 512 /* actual malloced size*/ ,...,...); // option-2

Question

  1. Which one of the two is better [between option-1/option-2] way of using buffer? I hope option-1 makes sense, as it has length/size of valid data bytes of send buffer or "test_buff" in this case.

Thanks for your time and input.

Best Answer

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).

Related Topic