malloc - C programming, error in getting value using container_of() macro -
i have created following code understand offsetof() , container_of() macros. here printf() show 2 different address instead of same address. doing wrong?
#include <stdio.h> #include <stddef.h> typedef unsigned char byte; #define container(ptr, type, member) \ ({ \ (type *)((byte *)ptr - offsetof(type, member)); \ }) typedef struct { size_t size; void *block; }header; int main() { void *ptr = malloc(3); header *phdr = container(ptr, header, block); printf("%p %p\n", ptr, phdr->block); return 0; }
it looks code attempting inspect/demonstrate inner workings of malloc implementation. container
macro working, problem header
structure definition incorrect:
typedef struct { size_t size; void* block; } header;
this implying malloc
keeps size of allocation in memory followed pointer block. not accurate - assuming level of indirection not exist. code ends interpreting contents of data block void*
. since haven't initialized memory, see whatever happens there (from values gave, looks may seeing pointer next free block - when malloc(0)
you're not allowed write data block implementation may use - see struct malloc_chunk
in glibc malloc implementation example).
a more correct structure definition (works me on both clang-503.0.40/llvm 5.1 , vc 2012) be:
typedef struct { size_t size; char block[0]; } header;
you need change printf
print address of block
:
printf("%p %p\n", ptr, &phdr->block);
do note, of course, there no guarantee every malloc
implementation store block size before block, may not work.
Comments
Post a Comment