working of memset() function

Discussion in 'C' started by sureshN, May 25, 2007.

  1. sureshN

    sureshN New Member

    Joined:
    May 25, 2007
    Messages:
    2
    Likes Received:
    0
    Trophy Points:
    0
    The prototype for the function goes like this and it fills the first n bytes of the memory area pointed to be s with the constant byte c.

    void *memset(void *s, int c, size_t n);

    If you look at the implementation of the function, the second parameter is converted to ‘unsigned char’ so as to fill the memory with bytes.

    I have few questions regarding the design of this function:

    -Why does the function take integer as the parameter and later converts it into unsigned char? The function could have accepted the parameter as ‘unsigned char’ directly.

    -Does it not add confusion to the user of this function to look at the parameter as integer and then pass the integer and expect the same to be filled in the memory? For example considering integer of 4 bytes, the user might pass 0xAABBCCDD to be filled in the memory bytes but the function truncates and fill 0xDD in the memory.

    Any ideas or guesses?
     
  2. NewsBot

    NewsBot New Member

    Joined:
    Dec 2, 2008
    Messages:
    1,267
    Likes Received:
    2
    Trophy Points:
    0
    I would argue on your both the points.
    As per MSDN its Character to set to the memory and so integer means the ASCII value of the character as an input and so the valid range is always a positive and so unsigned char is as desired.

    when passing 0xAABBCCDD as second parameter its not what is expected (as MSDN clearly says what it does)
     
  3. sureshN

    sureshN New Member

    Joined:
    May 25, 2007
    Messages:
    2
    Likes Received:
    0
    Trophy Points:
    0
    Thanks Shabbir. What is concerning is the way it is designed. I am trying to understand under what circumstances this was designed when the ANSI standard was formed? My argument is why can't the second paramter be 'unsigned char' instead of an 'int'? In this way there is no confusion at all as to what range of values would the function take. Anyway it is converted to unsigned char inside. Why after so many years of forming a standard it is left the same?
     
  4. NewsBot

    NewsBot New Member

    Joined:
    Dec 2, 2008
    Messages:
    1,267
    Likes Received:
    2
    Trophy Points:
    0
    memset is a C function and probably because of backward compatibility.

    MS decided to make C# a new language and not a have a predecessors because it did not wanted to mess the things up with the backward compatibility issue like the one you are pointing out.
     

Share This Page

  1. This site uses cookies to help personalise content, tailor your experience and to keep you logged in if you register.
    By continuing to use this site, you are consenting to our use of cookies.
    Dismiss Notice