Thread: Simple Question on Correct Usage of memset

  1. #1
    Registered User deadpoet's Avatar
    Join Date
    Jan 2004
    Posts
    50

    Question Simple Question on Correct Usage of memset

    Hello to All,

    Here is a simple question related to memset. I have seen various methods used when using memset now, I want to know the correct manner. Lets say you have the following code:

    Code:
    char *ptrFoo;
    
    ...
    
    ptrFoo = new char [ (strlen( SOME_CHAR_STRING ) + 1 ) ];
    memset( ptrFoo, 0, sizeof( ptrFoo ) );
    I have seen where some have used memset in a manner like sizeof( ptrFoo ) +1. Now which is it? Should one memset the additional element used for the null or not?

    Thanks,

    DeadPoet

  2. #2
    Code Goddess Prelude's Avatar
    Join Date
    Sep 2001
    Posts
    9,897
    Using sizeof as the size argument will only work for arrays. For dynamically allocated memory you need to give the same size argument as you gave to new:
    Code:
    char *p;
    ...
    p = new char[strlen ( SOME_STRING ) + 1];
    memset ( p, 0, strlen ( SOME_STRING ) + 1 );
    Your current code only takes the sizeof a pointer, which would be something small like 4.

    >Should one memset the additional element used for the null or not?
    It depends on the value you set the other elements to. If it's 0 then it couldn't hurt. If it's not 0 then there's no real point because you'll have to set it to 0 separately. However, memset for strings isn't really needed as you can allocate the memory and make the string empty by setting the first character to '\0':
    Code:
    char *p;
    ...
    p = new char[strlen ( SOME_STRING ) + 1];
    *p = '\0;
    The effect is the same as long as you treat p as the start of the string when you begin to work with it.
    My best code is written with the delete key.

  3. #3
    Registered User deadpoet's Avatar
    Join Date
    Jan 2004
    Posts
    50
    Prelude, as always you have provided a solid answer to my question. Thanks for all your assistance.

    DeadPoet

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Simple Question!!
    By gameuser in forum C++ Programming
    Replies: 2
    Last Post: 06-06-2009, 05:42 PM
  2. Very simple question, problem in my Code.
    By Vber in forum C Programming
    Replies: 7
    Last Post: 11-16-2002, 03:57 PM
  3. Inheritance related question. Is this correct?
    By Unregistered in forum C++ Programming
    Replies: 1
    Last Post: 07-19-2002, 04:30 AM
  4. I have a Question about memory usage for C.
    By bobthefish3 in forum C Programming
    Replies: 34
    Last Post: 12-24-2001, 04:37 PM
  5. A Simple Question
    By Unregistered in forum Windows Programming
    Replies: 1
    Last Post: 10-26-2001, 05:23 PM