상단 바이트를 그대로 유지하면서 4 바이트 길이의 바닥 3 바이트를 어떻게 설정할 수 있습니까?

StackOverflow https://stackoverflow.com/questions/1806764

  •  05-07-2019
  •  | 
  •  

문제

관련 코드는 다음과 같습니다.

typedef unsigned long int chunk_head;

typedef struct malloc_chunk
{
    // Contains the size of the data in the chunk and the flag byte.
    chunk_head      head;

    // Deliberately left unsized to allow overflow. 
    // Contains the payload of the chunk.
    unsigned int    data[];
};

예를 들어, "Get"매크로는 다음과 같습니다.

//Get the size of the data contained within the chunk.
#define GET_CHUNK_SIZE(chunk) ((chunk.head) & 0xFFFFFF)

깃발에 비트를 사용하는 상단 바이트 - "Inuse"및 "Coalesced 될 수 있습니다"라는 비트를 사용하고 있으며 내가 찾은 추가 기능이 유용합니다.

제목에 명시된 바와 같이 배경 정보를 제공하기 때문에 하단 3 바이트를 덩어리가 얼마나 큰지 변경할 수 있어야합니다. 나의 초기 본능은 크기가 적절하게 정렬되기 때문에 크기를 가진 헤더와 크기를 가진 헤더였습니다. 그러나 크기가 길고 길이와 일치 할 때까지 자동으로 예로를 배정했기 때문에 플래그 바이트를 덮어 쓸 수 있다는 것을 깨달았습니다. 나는 당신조차 확실하지 않습니다 ~할 수 있다 비트와 int와 긴. 어쨌든 대단히 감사합니다.

도움이 되었습니까?

해결책

How about:

head = (head & 0xff000000) | (new_size & 0x00ffffff)

다른 팁

For some reason most of the responses you received so far insist on sweeping the potential size overflow issue under the carpet, i.e. they "and" the chunk size with 0x00FFFFFF thus quietly discarding the excessive size bits (if any) and then proceed to write the completely meaningless tail portion of the size into the field. I don't know why would anyone do something like that.

The more reasonable code might look as follows

assert((size & 0xFF000000) == 0);
chunk.head = (chunk.head & 0xFF000000) | size;

There is no valid reason to "and" the size with 0x00FFFFFF. You should either abort or at least assert on excessive size, not quietly discard the excess.

Use bit fields to do this. It avoids having to use the macros, nice in the debugger too:

typedef struct chunk_head {
  unsigned size:24;
  unsigned inuse:1;
  unsigned cancoalesce:1;
  // Room for 6 more...
};

typedef struct malloc_chunk {
  struct chunk_head head;
  int data[];
};

chunk.head = (chunk.head & ~0xffffffL) | (new_lower_bits)

// retain the old top 8 bits
chunk.head &= 0xFF00000000

// set the lower 24 bits
chunk.head |= (0x00FFFFFF & new_bits)
#define SET_CHUNK_SIZE(chunk, size) (chunk.head = (chunk.head & 0xFF000000) | (size & 0x00FFFFFF))

Is that what you meant or did I miss something?

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