Correct way to use ZeroMemory.

This is a discussion on Correct way to use ZeroMemory. within the Windows Programming forums, part of the Platform Specific Boards category; Which way is the correct way to handle this. TCHAR szString[100]; 1. ZeroMemory(&szString, sizeof(szString)); 2. ZeroMemory(&szString, sizeof(TCHAR) * sizeof(szString)); 3. ...

  1. #1
    Unreggistered
    Guest

    Correct way to use ZeroMemory.

    Which way is the correct way to handle this.

    TCHAR szString[100];

    1. ZeroMemory(&szString, sizeof(szString));

    2. ZeroMemory(&szString, sizeof(TCHAR) * sizeof(szString));

    3. Something else all together.

  2. #2
    Confused Magos's Avatar
    Join Date
    Sep 2001
    Location
    Sweden
    Posts
    3,145
    ZeroMemory(szString, sizeof(TCHAR) * sizeof(szString));

    The size should be expressed in bytes, so to be correct you should use sizeof(), though a char only takes one byte.

    szString is basically a pointer, so you don't get it's adress using &.
    MagosX.com

    Give a man a fish and you feed him for a day.
    Teach a man to fish and you feed him for a lifetime.

  3. #3
    Registered User
    Join Date
    Sep 2002
    Posts
    272
    >ZeroMemory(szString, sizeof(TCHAR) * sizeof(szString));<


    Say we had a unicode array -

    TCHAR t[255];


    sizeof(TCHAR) would equal 2.
    sizeof(t) would equal 510.

    Using the above method you'd be zero-ing 1020 bytes. This isn't what you want.

    The sizeof operator will produce the number of bytes in an array. All you need is -

    ZeroMemory(szString,sizeof(szString));
    Joe

  4. #4
    &TH of undefined behavior Fordy's Avatar
    Join Date
    Aug 2001
    Posts
    5,789
    My favorite way...if using C++


    TCHAR szString[100] = {0};

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Linux for GNU/Linux is not correct?
    By password636 in forum Linux Programming
    Replies: 8
    Last Post: 03-31-2009, 09:30 PM
  2. Is this correct : passing strings?
    By socket in forum C Programming
    Replies: 15
    Last Post: 11-25-2008, 02:03 PM
  3. GetOpenFileName() ZeroMemory error?
    By Bleech in forum Windows Programming
    Replies: 6
    Last Post: 12-06-2005, 04:45 PM
  4. memset() or ZeroMemory()
    By jdinger in forum C++ Programming
    Replies: 2
    Last Post: 05-10-2002, 10:38 AM
  5. Why I couldn't see the correct format of a file?
    By miketv in forum C Programming
    Replies: 2
    Last Post: 01-23-2002, 10:59 PM

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