Click to See Complete Forum and Search --> : Nulling a buffer memset or cBuffer[0]='\0'; ?????


billfor
June 14th, 2002, 05:03 PM
Hello, I am using a character bugger rebeatedly in my program.
How should I null out my buffer, and when?? Also,
should I use memset or should I do this: I cBuffer[0]='\0';


I am confused about this, so your help would be deeply
appreciated.

Paul McKenzie
June 14th, 2002, 05:19 PM
There is a difference. Doing buffer[0] = '\0' just sets the first byte of the buffer to 0, it doesn't NULL out anything except the first byte.

The memset sets the buffer with whatever character you specify. You need to specify the length.

Which one to choose? That's up to you and what you're program is doing. Maybe you should just use (if you're using C++) std::string and not worry about which to choose.

Regards,

Paul McKenzie

Anthony Mai
June 15th, 2002, 10:47 AM
Use buffer[0] = 0 will be faster. But it will only set the first char to NULL. If your buffer contains a null terminated string, usually that is sufficient enough, unless you use memcpy() to copy string, and you do not copy the null terminator.

It is a good practice to always nullify the first character when you initialize a buffer. But normally there is no need to nullify every thing especially when the next thing you do is fill up the buffer with something.

Do NOT use memset to nullify a buffer, if the buffer is used to contain data for which 0 is legitimate data, for example audio data. Instead, you should have separate variables to indicate whether the buffer contains any data or is it empty.