I need your help in understanding the memset behaviour.
char *data = malloc(40);
memset(data,1,40);
When I saw the data content it was 010101010101010 till the end of the size.Then i changed to this.
memset(data,~0,40);
I saw the correct content as 11111111 till end . What is the difference between the the setting of value as 1 and ~0. thanks for your time.
memset fills each byte of the provided memory region with the value you specify. Please note that only the least significant byte of the last argument is taken to populate the memory block (even though its type is int).
In your first case this byte is 0x01, while int the second case it's 0xFF (all ones). That's why you are observing this kind of difference.
I think you may be confusing bitwise not (~) with logical not (!).
~0 inverts all the bits, giving you -1 (all bits set)
!0 would give you 1.
Having said which, I don't see you you could be seeing '0101...' and '1111...', unless you are inadvertently giving the first output in hex and the second in binary. I'd expect to see either '0101...' and 'ffff...' or '00000010000001...' and '1111111111111111...'.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With