Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C string null terminator in oversized buffer

Note:

This is a question about pure C. No C++ functions, etc.


Question:

Suppose I malloc a buffer that has room for 100 chars. Then, I fill only 5 of those slots with actual chars. I've heard that best practice is to null all remaining slots in the buffer like this:

while (nextAvailableBufferSlot < currentBufferSize) 
{
    buffer[nextAvailableBufferSlot] = '\0';
    nextAvailableBufferSlot++;
}

Is this strictly necessary, or can I simply set buffer[5] = '\0' and save myself a loop?


Context:

The code in question is called very frequently with a buffer size of 4096 and 99% of the strings that get copied into it are much shorter, making the loop above run nearly every time for at least a couple thousand iterations.

It is NOT possible for me to know what size the strings are in advance. And because re-allocs are so expensive, I choose a large buffer size initially. I target desktop-class hardware, so memory is not constrained at all.

like image 465
Bryan Avatar asked Mar 31 '26 18:03

Bryan


1 Answers

If it's strings you are copying you can use strncpy to copy the string and the extra buffer space will be filled with \0 for you.

If for whatever reason you are using strcpy or copying the string by hand then yes, you can save yourself the loop because all standard string operations (strlen, strcpy, etc) will stop at the first \0 anyway.

like image 116
Francisco Soto Avatar answered Apr 03 '26 08:04

Francisco Soto



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!