How to determine the alignment an object would like












1















I have a previously allocated chunk of memory that I want to interpret in-place as a struct. How could I determine the memory address within the chunk that has the friendliest alignment for the struct?



Just need to know the mechanism for determining what byte boundary a given struct would work best within, basically.



// psuedo-code

struct Object{
int theseMembersCould;
double beAnything;
char itsJustData[69];
}

// a chunk of previously allocated memory that I want to use
std::vector<uint8> block;
block.resize(1024);

uint32 byteBoundary = ????; // <-- this is what I want to discover

// math to get the nearest addr on the boundary (assumes byteBoundary will be POW2)
uint32 alignmentOffset= (byteBoundary - (block.data() & byteBoundary-1u)) & byteBoundary-1u;

Object * obj = new (block.data() + alignmentOffset) Object;
obj->itsJustData = "used as if it were a normal object beyond this point";









share|improve this question

























  • C++11 and later, look up the alignof operator, alignas specifier, and std::aligned_storage type trait. Plenty of information, with examples, on various C++ reference sites. In combination, they can most likely be used to achieve what you need.

    – Peter
    Dec 28 '18 at 16:24
















1















I have a previously allocated chunk of memory that I want to interpret in-place as a struct. How could I determine the memory address within the chunk that has the friendliest alignment for the struct?



Just need to know the mechanism for determining what byte boundary a given struct would work best within, basically.



// psuedo-code

struct Object{
int theseMembersCould;
double beAnything;
char itsJustData[69];
}

// a chunk of previously allocated memory that I want to use
std::vector<uint8> block;
block.resize(1024);

uint32 byteBoundary = ????; // <-- this is what I want to discover

// math to get the nearest addr on the boundary (assumes byteBoundary will be POW2)
uint32 alignmentOffset= (byteBoundary - (block.data() & byteBoundary-1u)) & byteBoundary-1u;

Object * obj = new (block.data() + alignmentOffset) Object;
obj->itsJustData = "used as if it were a normal object beyond this point";









share|improve this question

























  • C++11 and later, look up the alignof operator, alignas specifier, and std::aligned_storage type trait. Plenty of information, with examples, on various C++ reference sites. In combination, they can most likely be used to achieve what you need.

    – Peter
    Dec 28 '18 at 16:24














1












1








1








I have a previously allocated chunk of memory that I want to interpret in-place as a struct. How could I determine the memory address within the chunk that has the friendliest alignment for the struct?



Just need to know the mechanism for determining what byte boundary a given struct would work best within, basically.



// psuedo-code

struct Object{
int theseMembersCould;
double beAnything;
char itsJustData[69];
}

// a chunk of previously allocated memory that I want to use
std::vector<uint8> block;
block.resize(1024);

uint32 byteBoundary = ????; // <-- this is what I want to discover

// math to get the nearest addr on the boundary (assumes byteBoundary will be POW2)
uint32 alignmentOffset= (byteBoundary - (block.data() & byteBoundary-1u)) & byteBoundary-1u;

Object * obj = new (block.data() + alignmentOffset) Object;
obj->itsJustData = "used as if it were a normal object beyond this point";









share|improve this question
















I have a previously allocated chunk of memory that I want to interpret in-place as a struct. How could I determine the memory address within the chunk that has the friendliest alignment for the struct?



Just need to know the mechanism for determining what byte boundary a given struct would work best within, basically.



// psuedo-code

struct Object{
int theseMembersCould;
double beAnything;
char itsJustData[69];
}

// a chunk of previously allocated memory that I want to use
std::vector<uint8> block;
block.resize(1024);

uint32 byteBoundary = ????; // <-- this is what I want to discover

// math to get the nearest addr on the boundary (assumes byteBoundary will be POW2)
uint32 alignmentOffset= (byteBoundary - (block.data() & byteBoundary-1u)) & byteBoundary-1u;

Object * obj = new (block.data() + alignmentOffset) Object;
obj->itsJustData = "used as if it were a normal object beyond this point";






c++ memory memory-alignment






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Dec 28 '18 at 16:31







Anne Quinn

















asked Dec 28 '18 at 16:17









Anne QuinnAnne Quinn

4,53563063




4,53563063













  • C++11 and later, look up the alignof operator, alignas specifier, and std::aligned_storage type trait. Plenty of information, with examples, on various C++ reference sites. In combination, they can most likely be used to achieve what you need.

    – Peter
    Dec 28 '18 at 16:24



















  • C++11 and later, look up the alignof operator, alignas specifier, and std::aligned_storage type trait. Plenty of information, with examples, on various C++ reference sites. In combination, they can most likely be used to achieve what you need.

    – Peter
    Dec 28 '18 at 16:24

















C++11 and later, look up the alignof operator, alignas specifier, and std::aligned_storage type trait. Plenty of information, with examples, on various C++ reference sites. In combination, they can most likely be used to achieve what you need.

– Peter
Dec 28 '18 at 16:24





C++11 and later, look up the alignof operator, alignas specifier, and std::aligned_storage type trait. Plenty of information, with examples, on various C++ reference sites. In combination, they can most likely be used to achieve what you need.

– Peter
Dec 28 '18 at 16:24












2 Answers
2






active

oldest

votes


















3














The alignof operator will tell you the alignment required by a type. For example const auto byteBoundary = alignof(Object);.



Consider using std::aligned_storage if you need to create aligned raw memory. You will also need to use placement new to properly being the lifetime of the Object you are trying to use block as.






share|improve this answer
























  • Ah, I see, changed the code to use placement new

    – Anne Quinn
    Dec 28 '18 at 16:32











  • @AnneQuinn Remember that by using new, your object will not be automatically destroyed. But using delete would also be problematic, as you are not suppose to release the memory like you would normally. You need to manually call your object's destructor when you are done with it with obj->~Object();.

    – François Andrieux
    Dec 28 '18 at 16:34





















2














Firs off, you attempted use of reinterpret_cast is incorrect, as it leads to undefined behavior due to strict aliasing rule violation. Instead, you should use placement new.



To properly align your struct, you can use std::align together with std::alignof.






share|improve this answer























    Your Answer






    StackExchange.ifUsing("editor", function () {
    StackExchange.using("externalEditor", function () {
    StackExchange.using("snippets", function () {
    StackExchange.snippets.init();
    });
    });
    }, "code-snippets");

    StackExchange.ready(function() {
    var channelOptions = {
    tags: "".split(" "),
    id: "1"
    };
    initTagRenderer("".split(" "), "".split(" "), channelOptions);

    StackExchange.using("externalEditor", function() {
    // Have to fire editor after snippets, if snippets enabled
    if (StackExchange.settings.snippets.snippetsEnabled) {
    StackExchange.using("snippets", function() {
    createEditor();
    });
    }
    else {
    createEditor();
    }
    });

    function createEditor() {
    StackExchange.prepareEditor({
    heartbeatType: 'answer',
    autoActivateHeartbeat: false,
    convertImagesToLinks: true,
    noModals: true,
    showLowRepImageUploadWarning: true,
    reputationToPostImages: 10,
    bindNavPrevention: true,
    postfix: "",
    imageUploader: {
    brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
    contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
    allowUrls: true
    },
    onDemand: true,
    discardSelector: ".discard-answer"
    ,immediatelyShowMarkdownHelp:true
    });


    }
    });














    draft saved

    draft discarded


















    StackExchange.ready(
    function () {
    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53961346%2fhow-to-determine-the-alignment-an-object-would-like%23new-answer', 'question_page');
    }
    );

    Post as a guest















    Required, but never shown

























    2 Answers
    2






    active

    oldest

    votes








    2 Answers
    2






    active

    oldest

    votes









    active

    oldest

    votes






    active

    oldest

    votes









    3














    The alignof operator will tell you the alignment required by a type. For example const auto byteBoundary = alignof(Object);.



    Consider using std::aligned_storage if you need to create aligned raw memory. You will also need to use placement new to properly being the lifetime of the Object you are trying to use block as.






    share|improve this answer
























    • Ah, I see, changed the code to use placement new

      – Anne Quinn
      Dec 28 '18 at 16:32











    • @AnneQuinn Remember that by using new, your object will not be automatically destroyed. But using delete would also be problematic, as you are not suppose to release the memory like you would normally. You need to manually call your object's destructor when you are done with it with obj->~Object();.

      – François Andrieux
      Dec 28 '18 at 16:34


















    3














    The alignof operator will tell you the alignment required by a type. For example const auto byteBoundary = alignof(Object);.



    Consider using std::aligned_storage if you need to create aligned raw memory. You will also need to use placement new to properly being the lifetime of the Object you are trying to use block as.






    share|improve this answer
























    • Ah, I see, changed the code to use placement new

      – Anne Quinn
      Dec 28 '18 at 16:32











    • @AnneQuinn Remember that by using new, your object will not be automatically destroyed. But using delete would also be problematic, as you are not suppose to release the memory like you would normally. You need to manually call your object's destructor when you are done with it with obj->~Object();.

      – François Andrieux
      Dec 28 '18 at 16:34
















    3












    3








    3







    The alignof operator will tell you the alignment required by a type. For example const auto byteBoundary = alignof(Object);.



    Consider using std::aligned_storage if you need to create aligned raw memory. You will also need to use placement new to properly being the lifetime of the Object you are trying to use block as.






    share|improve this answer













    The alignof operator will tell you the alignment required by a type. For example const auto byteBoundary = alignof(Object);.



    Consider using std::aligned_storage if you need to create aligned raw memory. You will also need to use placement new to properly being the lifetime of the Object you are trying to use block as.







    share|improve this answer












    share|improve this answer



    share|improve this answer










    answered Dec 28 '18 at 16:25









    François AndrieuxFrançois Andrieux

    15.6k32647




    15.6k32647













    • Ah, I see, changed the code to use placement new

      – Anne Quinn
      Dec 28 '18 at 16:32











    • @AnneQuinn Remember that by using new, your object will not be automatically destroyed. But using delete would also be problematic, as you are not suppose to release the memory like you would normally. You need to manually call your object's destructor when you are done with it with obj->~Object();.

      – François Andrieux
      Dec 28 '18 at 16:34





















    • Ah, I see, changed the code to use placement new

      – Anne Quinn
      Dec 28 '18 at 16:32











    • @AnneQuinn Remember that by using new, your object will not be automatically destroyed. But using delete would also be problematic, as you are not suppose to release the memory like you would normally. You need to manually call your object's destructor when you are done with it with obj->~Object();.

      – François Andrieux
      Dec 28 '18 at 16:34



















    Ah, I see, changed the code to use placement new

    – Anne Quinn
    Dec 28 '18 at 16:32





    Ah, I see, changed the code to use placement new

    – Anne Quinn
    Dec 28 '18 at 16:32













    @AnneQuinn Remember that by using new, your object will not be automatically destroyed. But using delete would also be problematic, as you are not suppose to release the memory like you would normally. You need to manually call your object's destructor when you are done with it with obj->~Object();.

    – François Andrieux
    Dec 28 '18 at 16:34







    @AnneQuinn Remember that by using new, your object will not be automatically destroyed. But using delete would also be problematic, as you are not suppose to release the memory like you would normally. You need to manually call your object's destructor when you are done with it with obj->~Object();.

    – François Andrieux
    Dec 28 '18 at 16:34















    2














    Firs off, you attempted use of reinterpret_cast is incorrect, as it leads to undefined behavior due to strict aliasing rule violation. Instead, you should use placement new.



    To properly align your struct, you can use std::align together with std::alignof.






    share|improve this answer




























      2














      Firs off, you attempted use of reinterpret_cast is incorrect, as it leads to undefined behavior due to strict aliasing rule violation. Instead, you should use placement new.



      To properly align your struct, you can use std::align together with std::alignof.






      share|improve this answer


























        2












        2








        2







        Firs off, you attempted use of reinterpret_cast is incorrect, as it leads to undefined behavior due to strict aliasing rule violation. Instead, you should use placement new.



        To properly align your struct, you can use std::align together with std::alignof.






        share|improve this answer













        Firs off, you attempted use of reinterpret_cast is incorrect, as it leads to undefined behavior due to strict aliasing rule violation. Instead, you should use placement new.



        To properly align your struct, you can use std::align together with std::alignof.







        share|improve this answer












        share|improve this answer



        share|improve this answer










        answered Dec 28 '18 at 16:25









        SergeyASergeyA

        41.6k53783




        41.6k53783






























            draft saved

            draft discarded




















































            Thanks for contributing an answer to Stack Overflow!


            • Please be sure to answer the question. Provide details and share your research!

            But avoid



            • Asking for help, clarification, or responding to other answers.

            • Making statements based on opinion; back them up with references or personal experience.


            To learn more, see our tips on writing great answers.




            draft saved


            draft discarded














            StackExchange.ready(
            function () {
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53961346%2fhow-to-determine-the-alignment-an-object-would-like%23new-answer', 'question_page');
            }
            );

            Post as a guest















            Required, but never shown





















































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown

































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown







            Popular posts from this blog

            Mossoró

            Error while reading .h5 file using the rhdf5 package in R

            Pushsharp Apns notification error: 'InvalidToken'