0

Here is a code out of curiosity.

I'm trying to figure out how to access my allocation metadata. When I do chunk = second_alloc - sizeof (struct malloc_chunk); I manage to recover information, but if I do chunk = first_alloc - sizeof (struct malloc_chunk); I do not collect any information of the first memory allocation (all is 0, Why?)...

The second question is why when I do first_alloc - second_alloc = 32

I have an offset of 32 bytes; doesn't the metadata structure count? However the chunk_malloc structure has a size of 48 bytes ... (on 64 bit proc);

Shouldn't the chunk_malloc structure be included in it?

#include <stdlib.h>
#include <stdio.h>

typedef size_t  INTERNAL_SIZE_T;

struct malloc_chunk {
    INTERNAL_SIZE_T      mchunk_prev_size;  /* Size of previous chunk (if free).  */
    INTERNAL_SIZE_T      mchunk_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(void) {
    struct malloc_chunk     *chunk;
    void            *second_alloc;
    void            *first_alloc = malloc(10);

    second_alloc = malloc(10);
    chunk = second_alloc - sizeof(struct malloc_chunk);
    free(second_alloc);
    free(first_alloc);

    printf("bk %p\n", chunk->bk);
    printf("fd %p\n", chunk->fd);
    printf("prev_size: %li\n", chunk->mchunk_prev_size);
    printf("chunk_size: %li\n", chunk->mchunk_size);
    return (0);
}
trincot
  • 317,000
  • 35
  • 244
  • 286
Blue
  • 25
  • 1
  • 4
  • This is obviously something about your particular system's implementation of `malloc`, but you haven't told us what system it is... OS, compiler, standard library, versions? – Nate Eldredge Dec 15 '19 at 18:53
  • The answer will probably come from carefully reading the source code of your standard library's `malloc` implementation, or perhaps single-stepping through it. It may be that it doesn't always use the `malloc_chunk` structure the way you think it does. – Nate Eldredge Dec 15 '19 at 18:56

0 Answers0