1

malloc で使われているチャンク構造体を探したい

ソースコードによると、次のようになります。

struct malloc_chunk {

  INTERNAL_SIZE_T      prev_size;  /* Size of previous chunk (if free).  */
  INTERNAL_SIZE_T      size;       /* Size in bytes, including overhead. */

  struct malloc_chunk* fd;         /* double links -- used only if free. */
  struct malloc_chunk* bk;

  /* Only used for large blocks: pointer to next larger size.  */
  struct malloc_chunk* fd_nextsize; /* double links -- used only if free. */
  struct malloc_chunk* bk_nextsize;
}

しかし、このコードは無効な読み取りを行います:

int main()
{
  struct malloc_chunk *chunk;
  void                *ptr;

  ptr = malloc(10);
  chunk = ptr - sizeof(struct malloc_chunk);
  printf("%p\n", chunk->fd);
}

次に、これでチャンクサイズを見つけようとしました:

int main()
{
   void  *ptr1;
   void  *ptr2;

   ptr1 = malloc(10);
   ptr2 = malloc(10);

   printf("%d\n", ptr2 - ptr1 - 10);
}

そして、私はサイズを取得します:

  • 10:22
  • 500:12
  • 31:31

malloc のメタデータを取得するにはどうすればよいですか?

4

1 に答える 1

4

宣言の直後のコメントをmalloc_chunk見ると、次のことがわかります。

/*
malloc_chunk details:

(The following includes lightly edited explanations by Colin Plumb.)

Chunks of memory are maintained using a `boundary tag' method as
described in e.g., Knuth or Standish. (See the paper by Paul
Wilson ftp://ftp.cs.utexas.edu/pub/garbage/allocsrv.ps for a
survey of such techniques.) Sizes of free chunks are stored both
in the front of each chunk and at the end. This makes
consolidating fragmented chunks into bigger chunks very fast. The
size fields also hold bits representing whether chunks are free or
in use.

An allocated chunk looks like this:


    chunk-> +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
            | Size of previous chunk, if allocated                        | |
            +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
            | Size of chunk, in bytes                                   |M|P|
      mem-> +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
            | User data starts here...                                      .
            .                                                               .
            . (malloc_usable_size() bytes)                                  .
            .                                                               |
nextchunk-> +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
            |  Size of chunk                                                |
            +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+

            ...

*/

それが言うところに注意してください"User data starts here..."-割り当てられたメモリブロックを扱うとき、ユーザーメモリブロックへのポインタは構造内で始まります。malloc_chunk

メモリ アロケータの実装 (特に製品の実装) では、多くの場合、ほとんどのコードで非常に悪いコーディング手法と見なされるハックが使用されます。これは、メモリ割り当てルーチンが非常に頻繁に使用され、時間とスペースのわずかな増加がプログラムのパフォーマンスに大きな違いをもたらすことが多いためです。

于 2014-02-03T19:15:09.090 に答える