2

I am working on a project that implements the buddy allocation algorithm in C. Using mmap(), I allocated a space of 1GB of continuous memory. It looks like this:

  char * base = mmap(NULL, MAX_MEM, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_ANON, 0, 0);

I have a struct that I am trying to place into that space. The struct looks like this:

typedef struct Node {
    unsigned char header;
    struct Node *next;
    struct Node *prev;

}node;

I am unsure how to get a node to go into that spot. I tried the code below because I didn't want to put the node at the very beginning, but when I print out the pointer they show much different spots

void *ptr = (struct Node *) base + 512;
printf("base: %p\n", base);
printf("ptr: %p\n", ptr);

My terminal window prints out this:

base: 0x102ef1000
ptr: 0x102ef4000

But this doesn't seem right because the pointers are 12288 spaces away from each other in memory instead of just 512. What am I doing wrong?

GoFlyers
  • 31
  • 2
  • 7
  • this line: void *ptr = ((struct Node *) base) + 512; should be: node *ptr = (node*)((char *)(base + 512)); humm, this editor keeps dropping the '*' in the (node*) – user3629249 Nov 06 '14 at 04:33

2 Answers2

1

Remember, as you cast base to a struct Node * adding to it will now add the size of a struct Node to the pointer, therefore you are adding sizeof(struct Node) * 512 to it. this is probably not what you want. Given it is a 24 byte struct this makes it 24 * 512 = 12288.

The reason it is 12 bytes is that is contains 2 8 byte pointers, a 1 byte char and 7 bytes of padding to ensure the pointers are aligned to 8 bytes.

To solve this simply omit the cast, it will leave base as a char * and increment it 512 bytes as wanted.

void *ptr = base + 512; 
Vality
  • 6,577
  • 3
  • 27
  • 48
1
void *ptr = (struct Node *) base + 512; 

means ((struct Node *) base) + 512.

What you want is

void *ptr = (struct Node *) (base + 512);

So you skip 512 bytes from the beginning of allocation.

According to the post, cast has higher precedence than addition.

Community
  • 1
  • 1
SSC
  • 1,311
  • 5
  • 18
  • 29
  • Thank you! One more question if you wouldn't mind. My struct has a property called "char header" now that my struct is in that dynamically allocated space, how do I access the header portion? I can't do ptr.header because it is just a pointer. – GoFlyers Nov 06 '14 at 03:28
  • You can either cast your `ptr` to `struct Node` as `((struct Node*)ptr)->header or change the `ptr` to the `struct Node *` type and do ptr->header. – SSC Nov 06 '14 at 03:36