问题
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
回答1:
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.
回答2:
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.
回答3:
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] );
}
回答4:
The trick with memcpy( ecx+1, ecx, ...
does not work here on Linux. Only 1 byte is copied instead of iterations-1
.
来源:https://stackoverflow.com/questions/1418857/memset-not-filling-array