CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 3 of 3
  1. #1
    Join Date
    Apr 2002
    Posts
    65

    Nulling a buffer memset or cBuffer[0]='\0'; ?????

    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.

  2. #2
    Join Date
    Apr 1999
    Posts
    27,449
    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

  3. #3
    Join Date
    Jun 1999
    Location
    San Diego, CA
    Posts
    600
    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.

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  





Click Here to Expand Forum to Full Width

Featured