Skip to content

Instantly share code, notes, and snippets.

@y-fedorov
Created February 24, 2017 21:11
Show Gist options
  • Save y-fedorov/0712f2d09e78ab0c48a67c80bcdffd80 to your computer and use it in GitHub Desktop.
Save y-fedorov/0712f2d09e78ab0c48a67c80bcdffd80 to your computer and use it in GitHub Desktop.
//
// main.cpp
// luxoft quiz application
//
// Created by Yaroslav Fedorov on 24/02/2017.
// Copyright © 2017 Yaroslav Fedorov. All rights reserved.
//
//
// LUXOFT task for C++ Russia 2017 contest
//
// Как получить информацию из закрытого члена класса? Решение должно быть
// платформонезависмым и компиляторонезависисмым (нет информации о том, как данные
// представленны в памяти)
#include <iostream>
class TopSecret
{
public:
TopSecret() : ultimateAnswerToLifeUniverseAndEverything(42) {}
private:
enum { NO, BYTE, MANIPULATION } nativeProtection;
std::string aroundTopSecretInformation;
int ultimateAnswerToLifeUniverseAndEverything;
double footer;
char terminator;
};
int getValue(const TopSecret& t)
{
int answer;
//#1 answer
struct TopSecretPrototype { enum {} nb; std::string s; int SecretValue; };
answer = reinterpret_cast<const TopSecretPrototype *>( &t )->SecretValue;
//#2 answer
char *p = (char*)&t;
enum X {};
answer = int(*(p + sizeof(enum X) + sizeof(std::string) + sizeof(int)));
//#3 answer
char *d = (char*)&t;
auto alignedChar = sizeof(char) + 3;
auto offset = sizeof(TopSecret) - sizeof(int *) - alignedChar - sizeof(double) - sizeof(int);
answer = int(*(d + offset));
return answer;
}
int main(int argc, const char * argv[]) {
std::cout <<
"Answer to the Ultimate Question of "
"Life, "
"the Universe, "
"and Everething is "
<< getValue( TopSecret() ) << std::endl;
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment