Reputation: 66
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
Upvotes: 0
Views: 103
Reputation: 36441
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
.
Upvotes: 3
Reputation: 145899
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.
Upvotes: 1