newbie: memset before snprintf

This is a discussion on newbie: memset before snprintf within the C Programming forums, part of the General Programming Boards category; hello gurus, I have the following code: char em[_POSIX_PATH_MAX]; memset(em, 0, _POSIX_PATH_MAX); snprintf(em, sizeof(em), "%s/db/abc", root_ptr); is memset needed here, ...

  1. #1
    Registered User
    Join Date
    Apr 2002
    Posts
    10

    Question newbie: memset before snprintf

    hello gurus,

    I have the following code:

    char em[_POSIX_PATH_MAX];
    memset(em, 0, _POSIX_PATH_MAX);
    snprintf(em, sizeof(em), "%s/db/abc", root_ptr);

    is memset needed here, or will snprintf work without any errors?

    thanks

  2. #2
    B26354 Deckard's Avatar
    Join Date
    Jan 2002
    Posts
    633

    Re: newbie: memset before snprintf

    Originally posted by webwesen
    is memset needed here, or will snprintf work without any errors?
    memset() is not needed. snprintf() will terminate the string with a null.
    Jason Deckard

  3. #3
    Registered User
    Join Date
    Apr 2002
    Posts
    10

    thnks

    thanks Jason!
    your help is appreciated

  4. #4
    ATH0 quzah's Avatar
    Join Date
    Oct 2001
    Posts
    14,826

    Re: Re: newbie: memset before snprintf

    Originally posted by Deckard
    memset() is not needed. snprintf() will terminate the string with a null.
    Additionally, you could just initialize your array in one shot at creation time.

    There are two ways to zero value an array. One will give you different end results, but initially, it will be zeroed:

    a) the better way:

    char em[SOMESIZE] = {0};

    b) the odd way:

    static char em[SOMESIZE];

    Now the second (b) will behave in a rather different way than you exepct, however, it would actually initialize the array to zero value the first time the function was called. (After that, it'd have whatever value you had left in it the time before.)

    Obviously the first is the way to go, but I thought I would throw the other out, becuse it does zero value it.

    Quzah.
    Hope is the first step on the road to disappointment.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. info on memset and recv
    By lolguy in forum Networking/Device Communication
    Replies: 15
    Last Post: 11-12-2009, 05:48 AM
  2. Simple Question on Correct Usage of memset
    By deadpoet in forum C++ Programming
    Replies: 2
    Last Post: 03-16-2004, 08:58 AM
  3. memset has conflicting declaration
    By mangoMan in forum C++ Programming
    Replies: 2
    Last Post: 03-02-2004, 10:08 AM
  4. Newbie Game Develpoers Unite!
    By Telenosis in forum Game Programming
    Replies: 10
    Last Post: 06-22-2002, 03:02 PM
  5. memset() or ZeroMemory()
    By jdinger in forum C++ Programming
    Replies: 2
    Last Post: 05-10-2002, 10:38 AM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21