# OSDev.org

The Place to Start for Operating System Developers
 It is currently Sat Jul 24, 2021 12:11 pm

 All times are UTC - 6 hours

 Page 1 of 1 [ 3 posts ]
 Print view Previous topic | Next topic
Author Message
 Post subject: [SOLVED Strange addition in C++/GCCPosted: Sat Jan 20, 2018 11:30 pm

Joined: Fri Oct 13, 2017 6:59 pm
Posts: 17
Hi there,

I'm using a struct to define a memory area like so:
Code:
typedef struct {
size_t size; // The size of the memory area
int magic; // Used to detect block header corruption
bool free; // The area is free ?
} block;

Each block is directly followed by the area of size block->size, and after it, we've got the next block.

To find the next block I just need to do p + p->size + sizeof(block) (p is a pointer to a block) yea ?
But I've got strange result :/
With p=0x106c74, p->size=0xff4 and sizeof(block)=0xc I should got 0x107c74 (as 0x106c74 + 0xff4 + 0xc = 0x106c74 + 0x1000). But when testing with GDB I've got 0x112c74 :/

Any idea ? GCC optimization are disabled. Did I miss something with c++ math ?

Last edited by Tutul on Sun Jan 21, 2018 1:10 am, edited 1 time in total.

Top

 Post subject: Re: Strange addition in C++/GCCPosted: Sun Jan 21, 2018 12:15 am
 Member

Joined: Wed Dec 01, 2010 3:41 am
Posts: 1761
Location: Hong Kong
c++ pointer arithmetic acknowledge the pointer type, if p is pointer to a block type, p + p->size means &p[p->size].

so, with sizeof(block) = 12 (32-bits, with padding)

Code:
p + p->size + sizeof(block)
= &p[p->size + sizeof(block)]
= 0x106c74 + (0xff4 + 0xc) * 12
= 0x106c74 + 0xc000
= 0x112c74

Top

 Post subject: Re: Strange addition in C++/GCCPosted: Sun Jan 21, 2018 1:08 am

Joined: Fri Oct 13, 2017 6:59 pm
Posts: 17
Oh I feel so stupid right now, didn't think about that. Thanks

Top

 Display posts from previous: All posts1 day7 days2 weeks1 month3 months6 months1 year Sort by AuthorPost timeSubject AscendingDescending
 Page 1 of 1 [ 3 posts ]

 All times are UTC - 6 hours

#### Who is online

Users browsing this forum: ebufuodi, MorrisGuasp and 6 guests

 You cannot post new topics in this forumYou cannot reply to topics in this forumYou cannot edit your posts in this forumYou cannot delete your posts in this forumYou cannot post attachments in this forum

Search for:
 Jump to:  Select a forum ------------------ Operating System Development    OS Development    OS Design & Theory    Announcements, Test Requests, & Job openings Everything Else    General Programming    General Ramblings    Auto-Delete Forum OSDev.org    OSDev Wiki    About this site