Search code examples
c++hexmemset

Memory layout in memset


I have this "buggy" code :

int arr[15];
memset(arr, 1, sizeof(arr));

memset sets each byte to 1, but since int is generally 4-bytes, it won't give the desired output. I know that each int in the array will we initalized to 0x01010101 = 16843009. Since I have a weak (very) understanding of hex values and memory layouts, can someone explain why it gets initialized to that hex value ? What will be the case if I have say, 4, in place of 1 ?


Solution

  • What memset does is

    Converts the value ch to unsigned char and copies it into each of the first count characters of the object pointed to by dest.

    So, first your value (1) will be converted to unsigned char, which occupies 1 byte, so that will be 0b00000001. Then memset will fill the whole array's memory with these values. Since an int takes 4 bytes on your machine, the value of each int int the array would be 00000001000000010000000100000001 which is 16843009. If you place another value instead of 1, the array's memory will be filled with that value instead.