문제

 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);

간단히 말해서, 내 출력이 왜 다음과 같은가?

0D0D0D0D
BAADF00D

추신 : U32는 서명되지 않은 int의 간단한 타이핑입니다.

편집하다:

  • GCC 컴파일 4.3.4
  • String.h가 포함되어 있습니다
도움이 되었습니까?

해결책

Memset의 두 번째 매개 변수는 int로 입력되지만 정말 서명되지 않은 숯. 0xBaADF00D가 부호되지 않은 숯으로 변환 (최소 유의 한 바이트)은 0x0D이므로 Memset은 0x0D로 메모리를 채 웁니다.

다른 팁

memset ()에 대한 두 번째 인수는 int 또는 u32가 아닌 char입니다. C는 0xBaADF00D int를 0x0D 숯으로 자동으로 자르고 요청 된대로 각 문자를 메모리에 설정합니다.

wmemset ()로 시도했습니다. 작동하는 것 같습니다.


#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] );
}

트릭 memcpy( ecx+1, ecx, ... Linux에서는 여기서 작동하지 않습니다. 대신 1 바이트 만 복사됩니다 iterations-1.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top