Question

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.

Was it helpful?

Solution

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.

OTHER TIPS

The short answer is yes you are right. You should really only need one null pointer that goes right after the last char in the array.

The typical answer would be, why not just use char pointers? A string-like char* takes care of the whole headache for you and there are libraries designed around manipulating these more easily. You don't need to allocate memory directly this way. Why do you have a specific reason for needed buffers of exactly 100?

For all practical purposes, you only need to NUL terminate the first position after the last position filled. That's all that's needed for any function to know where to stop when manipulation your string.

Use Calloc() function instead. It will automatically initialize the block of memory to zeros(i.e is equivalent of assigning NULL's, as ASCII code for NULL is 0).Then you will not need to explicitly assign each slot to Null.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top