foo_l
foo_l

Reputation: 601

memset behaviour

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.

Upvotes: 2

Views: 1878

Answers (3)

Whoami
Whoami

Reputation: 14408

Also, it can be verified in the gdb by the following way.

Code:

#include <stdio.h>
#include <string.h>

int main ()
{
 char *data = malloc  (20); 
 memset (data, 1, 20);
 printf (".... %s ", data);

  memset ( data, ~0, 20);
  printf (" \n .... %s.. ", data );


}

set break point to main.

GDB OUTPUT:

Breakpoint 1, main () at mymemset.c:6
6    char *data = malloc  (20); 

(gdb) n
7    memset (data, 1, 20);
(gdb) n
8    printf (".... %s ", data);
(gdb) x/20b data
0x1001008a0:    0x01    0x01    0x01    0x01    0x01    0x01    0x01    0x01
0x1001008a8:    0x01    0x01    0x01    0x01    0x01    0x01    0x01    0x01
0x1001008b0:    0x01    0x01    0x01    0x01
(gdb) n
10    memset ( data, ~0, 20);
(gdb) n
11    printf (" \n .... %s.. ", data );
(gdb) x/20b data
0x1001008a0:    0xff    0xff    0xff    0xff    0xff    0xff    0xff    0xff
0x1001008a8:    0xff    0xff    0xff    0xff    0xff    0xff    0xff    0xff
0x1001008b0:    0xff    0xff    0xff    0xff
(gdb) Quit

Upvotes: 1

Tom Tanner
Tom Tanner

Reputation: 9354

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...'.

Upvotes: 1

Maksim Skurydzin
Maksim Skurydzin

Reputation: 10541

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.

Upvotes: 8

Related Questions