Daniel Sloof
Daniel Sloof

Reputation: 12706

memset not filling array

 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:

Upvotes: 4

Views: 3359

Answers (4)

CoSoCo
CoSoCo

Reputation: 135

The trick with memcpy( ecx+1, ecx, ... does not work here on Linux. Only 1 byte is copied instead of iterations-1.

Upvotes: 0

sambowry
sambowry

Reputation: 2466

I tried it with wmemset(). It seems to work:


#include <stdlib.h>
#include <stdio.h>
#include <inttypes.h>
#include <wchar.h>

int main(void){
  uint32_t iterations = 5;
  uint32_t *ecx = (uint32_t*)malloc(sizeof(uint32_t) * iterations);

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

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

  /* Update: filling the array with memcpy() */
  ecx[0] = 0x11223344;
  memcpy( ecx+1, ecx, sizeof(*ecx) * (iterations-1) );
  printf("memcpy:   %.8X %.8X %.8X %.8X %.8X\n",
             ecx[0], ecx[1], ecx[2], ecx[3], ecx[4] );
}

Upvotes: 2

George Phillips
George Phillips

Reputation: 4654

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.

Upvotes: 2

Tadmas
Tadmas

Reputation: 6358

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.

Upvotes: 11

Related Questions