typedef enum { CPCLOCK, DLACLOCK, } clocksourcetype; typedef struct { uint32t blockid;…
- User
typedef enum { CP_CLOCK, DLA_CLOCK, } clock_source_type;
typedef struct { uint32_t block_id; uint32_t count_id; uint32_t npu_pc;
uint64_t cycle_start; uint64_t cycle_end;
clock_source_type clock_source; } attribute((packed, aligned)) befor;
typedef struct { uint32_t block_id; uint32_t count_id; uint32_t npu_pc;
uint64_t cycle_start; uint64_t cycle_end;
clock_source_type clock_source; char clock; } attribute((packed, aligned)) after; 위의 코드의 경우 clock이 추가되면서 16 커졌다 그 이유는 무엇인가?
- Assistant
코드에서
after구조체에 새로운 멤버char clock이 추가되었음에도 불구하고 메모리 크기가 16바이트 증가한 이유는 구조체의 패딩과 정렬 규칙 때문입니다. 다음은 자세한 이유 설명입니다.구조체는 특정 멤버들이 특정 방식으로 정렬되기를 요구함으로써 CPU가 올바르게 읽고 쓸 수 있게 설계되어 있습니다. 이 정렬 규칙은 플랫폼마다 약간씩 다를 수 있지만, 일반적으로는 대부분의 경우 메모리 주소가 데이터 타입의 배수에 맞게 정렬되도록 합니다.
예를 들어, 4바이트
uint32_t타입은 메모리에서 4의 배수 주소에 배치될 것이고, 8바이트 타입은 8의 배수 주소에 배치될 것입니다.