Search code examples
cstringpointersstrlenmemset

Using the memset() and interpreting the size_t num of the funciton


I am trying to decipher a block of code that uses memset(). Below is what I am trying to decipher.

memset(buffer, 0, strlen(argv[1]) - 4);

From my understanding of the memset function, it is to fill the block of memory of "buffer" with the value of "0" and return the size of the string stored in argv[1] -4. Can someone explain argv[1] -4?

I understand that argv[1] is the first array to be set into the buffer.

I used resources from this website.


Solution

  • From the man page, the syntax for memset() is

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

    and the corresponding description is

    The memset() function fills the first n bytes of the memory area pointed to by s with the constant byte c.

    So, as per the code,

    memset(buffer, 0, strlen(argv[1]) - 4);
    

    memset function, it is to fill the block of memory of "buffer"

    Right

    with the value of "0"

    Right. its 0, not "0", though.

    and return the size of the string stored in "argv[1] -4 "

    NO. the third argument of memset() is the size or amount of memory (in bytes) to be filled with the value supplied as the second argument.

    For clarity and readibility, we can re-write the same as below

    memset( buffer , 0 , (strlen(argv[1]) - 4) );
    

    That said, strlen(argv[1]) - 4 gives the length of the string held by argv[1], subtracted by 4. As very rightly suggested my Mr. @Paul R, this logic is most probably used to denote the filename without an extension / suffix (omit last 4 chars of the input string).