0

I have here a really weird issue:

typedef struct s_mem_chunk { void *addr; unsigned int size; short is_alloc; struct s_mem_chunk *prev; } t_mem_chunk; #include <stdio.h> #include <stdlib.h> int main() { t_mem_chunk *mem_chunk; mem_chunk = malloc(sizeof(*mem_chunk)); mem_chunk->prev = 0; printf("%x + %x = %x\n", mem_chunk->prev, sizeof(*mem_chunk), mem_chunk->prev + sizeof(*mem_chunk)); return 0; } 

So the code here should output: "0 + 18 = 18" And it output instead "0 + 18 = 240"

So I am wondering why, this is may cause by the sizeof ot I dont know... I request your help, thanks in advance for your time and have a nice evening ! :D

4
  • 1
    a pointer doesn't really know the size of what it is pointing at. the correct method to get the size would be: 'sizeof(t_mem_chunk)' Commented Jan 25, 2015 at 18:08
  • 1
    Pointer math is not the same as integer math. For example, see this answer. Commented Jan 25, 2015 at 18:10
  • 4
    @user3629249: sizeof(*mem_chunk) is a perfectly valid way to obtain the size of the type pointed to by mem_chunk. Commented Jan 25, 2015 at 18:10
  • Makes perfect sense: sizeof(t_mem_chunk) == 0x240/0x18 == 0x18 == 24. Commented Jan 25, 2015 at 18:26

2 Answers 2

3

You misinterpreted 0 + 18 = 240 which is the right result!

0 is the value of mem_chunk->prev. 18 is the size of your structure; beware that this is in hexa.

You have pointer arithmetic, so mem_chunk->prev + sizeof(*mem_chunk) is not 0+18 as usual but the address of an hypothetic 19-th element of an array starting at 0. So 0x18*0x18=0x240 in hexa. In pointer arithmetic, adding a number to a pointer calculates a move; the int serves as a distance from the pointer, and units for the distance is the type of objects the pointer points to. If you add 1 to an int pointer, you calculate the memory address one int after...

In your case: mem_chunk->prev+1 is not 1 but 0x18 and mem_chunk->prev+2 is not 2 but 0x30.

Also pay attention to the format and use %p for pointers and %lx (%zx in C99) for sizeof which returns a long int.

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks for your help and your advices, now I know what really happens here :)
sizeof yields a size_t, for which the length modifier (C99, afair) is z (as in %zx).
1

Your program invokes undefined behavior.

x conversion specifier requires an argument of type unsigned int but mem_chunk->prev is a pointer value. Same for mem_chunk->prev + sizeof(*mem_chunk) which does not perform integer arithmetic but pointer arithmetic and yields an invalid pointer.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.