Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

memset not filling array

Tags:

c

memset

 u32 iterations = 5;
 u32* ecx = (u32*)malloc(sizeof(u32) * iterations);

 memset(ecx, 0xBAADF00D, sizeof(u32) * iterations);
 printf("%.8X\n", ecx[0]);

 ecx[0] = 0xBAADF00D;
 printf("%.8X\n", ecx[0]);

 free(ecx);

Very simply put, why is my output the following?

0D0D0D0D
BAADF00D

ps: u32 is a simple typedef of unsigned int

edit:

  • Compiling with gcc 4.3.4
  • string.h is included
like image 400
Daniel Sloof Avatar asked Dec 08 '22 06:12

Daniel Sloof


2 Answers

The second parameter to memset is typed as an int but is really an unsigned char. 0xBAADF00D converted to an unsigned char (least significant byte) is 0x0D, so memset fills memory with 0x0D.

like image 113
Tadmas Avatar answered Dec 23 '22 18:12

Tadmas


The second argument to memset() is a char not a int or u32. C automatically truncates the 0xBAADF00D int into a 0x0D char and sets each character in memory as requested.

like image 41
George Phillips Avatar answered Dec 23 '22 19:12

George Phillips