0

In C programming, character buffers are used for string implementation. habitually we are clear the content before we use any character buffer in any scope. I need a clarification on cleaning a char buffer when the char buffer is using several times within the same scope. e.g. within the below function I am using char buffer[BUF_SIZE].

void function foo(char *p_char)
{
 char buffer[BUF_SIZE];
 memset(buffer, '\0', BUV_SIZE-1);
 strcpy(buffer, p_char);
 ..
 ..
 // after some codes.
 strcpy(buffer, "second time use of buffer");

}

in above function, buffer is used twice, at the second place do I need to call memset() to clean the previous content in buffer ? likewise when using a char buffer do I always clean it before assign a value (if values are assigning several times to the buffer within same scope) ?

Nish
  • 149
  • 2
  • 5
  • 13
  • I don't know who "we" is, but I don't "habitually clear the content" of a `char[]` before I use it. Actually I don't know that I ever do, if it's just strings. – Jonathon Reinhart Mar 28 '13 at 02:30

2 Answers2

1

If you don't set the buffer to null characters, then the characters after the null terminator may be garbage, but that usually doesn't matter, since when something reads a char * string, it typically stops at the null terminator.

Vaughn Cato
  • 63,448
  • 5
  • 82
  • 132
1

If you are using strcpy, then memset is not actually required. From the man strcpy page, it can be noted that

The strcpy() function copies the string pointed to by src, including the terminating null byte ('\0'), to the buffer pointed to by dest. The strings may not overlap, and the destination string dest must be large enough to receive the copy.

Since, \0 is also copied, you don't really require to do the memset, as for strings, a terminating NULL \0 character indicates the end of the string.

NOTE: If you plan to use strncpy, please do refer to this question: Why does strncpy not null terminate?

Community
  • 1
  • 1
Ganesh
  • 5,880
  • 2
  • 36
  • 54