Skip to content

Instantly share code, notes, and snippets.

@codenulls
Created November 23, 2018 14:21
Show Gist options
  • Select an option

  • Save codenulls/3e9d039573c0e36e812d702c8bcfb798 to your computer and use it in GitHub Desktop.

Select an option

Save codenulls/3e9d039573c0e36e812d702c8bcfb798 to your computer and use it in GitHub Desktop.

Revisions

  1. codenulls created this gist Nov 23, 2018.
    63 changes: 63 additions & 0 deletions PlayerClassMemoryLayout.cpp
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,63 @@
    // GTA_test.cpp : Defines the entry point for the console application.
    //

    #include "stdafx.h"
    #include <cstdio>
    #include <cstdint>

    class Player
    {
    public:
    char name[20]; // instance address + 0
    int skinID; // instance address + sizeof(name)
    float health; // instance address + sizeof(name) + sizeof(skinID)
    float armour; // instance address + sizeof(name) + sizeof(skinID) + sizeof(health)

    /*
    // assuming instance address is 0x500ACE65
    char name[20]; // 0x500ACE65 + 0
    int skinID; // 0x500ACE65 + 20
    float health; // 0x500ACE65 + 24
    float armour; // 0x500ACE65 + 28
    */

    Player(char * theName, int theSkinID, float theHealth, float theArmour)
    {
    memcpy(name, theName, sizeof(name));

    skinID = theSkinID;
    health = theHealth;
    armour = theArmour;
    }
    };

    int main()
    {
    // `myPlayer` is an instance here. We can also call it "object"
    Player myPlayer((char*)"She said she was 18", 100, 75.0, 8.8);

    std::printf("\nsize of `myPlayer`: %u | address of `myPlayer`: %p\n\n", sizeof(myPlayer), &myPlayer);

    // Simple and recommended way of accessing
    Player * pPlayer = &myPlayer;

    std::printf("\nName: %s\nSkin ID: %d\nHealth: %f\nArmour: %f\n\n", pPlayer->name, pPlayer->skinID, pPlayer->health, pPlayer->armour);

    //////////////////////////////////////////////////
    // An Alternative way to access the instance data
    //////////////////////////////////////////////////

    std::uint8_t* playerAddress = reinterpret_cast<std::uint8_t*> (&myPlayer);

    char* pName = (char*)playerAddress;
    int skinID = *(int*)(playerAddress + 20);
    float health = *(float*)(playerAddress + 24);
    float armour = *(float*)(playerAddress + 28);

    std::printf("\nAlternative way:\nName: %s\nSkin ID: %d\nHealth: %f\nArmour: %f\n\n", pName, skinID, health, armour);

    getchar();
    return 0;
    }