What does struct object represents? [closed] - c++

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 5 years ago.
Improve this question
#include<iostream>
using namespace std;
struct A{
int a;
int s;
};
int main()
{
A *S =new A();
A obj1=S[0];
printf(" 0x%x",obj1);
}
My question is when i see the out put it seems be 0x0;
and is some cases it becomes 0xFFFFFFFF
can someone explain?

Your program has undefined behavior, so is wrong (because what you pass to printf does not match the " 0x%x" format control string, since it has the wrong type); see also this answer.
Read Lattner's blog on undefined behavior (it also applies to C++)
Notice that printf is a C library function (so you need to #include <cstdio>). In genuine C++11, you would use some operator << on std::ostream-s, probably like
std::cout << obj1 << std::endl;
and that line won't compile (unless you define such an operator, which you should do).
To explain the actual behavior (which is non reproducible in general), you need to dive into implementation details (and you don't want to: if you did, study the source and object code of your particular program and C++ library, of your compiler, of your operating system, look into calling conventions, instruction set, ABIs, etc...). The displayed garbage value (e.g. 0xfffffff) is what happens to sit in some relevant processor register or memory location (on the call stack).
BTW, if you compiled with all warnings & debug info (e.g. g++ -Wall -Wextra -g with GCC) you'll get a warning. I strongly recommend to enable all warnings.
Notice that a struct A{ is the same as class A{public: so you could define some explicit constructor (which would initialize the fields) and some output operator<<:
struct A{
int a;
int s;
A(int aa=0, int ss=0) : a(aa), s(ss) {};
};
std::ostream operator << (std::ostream&out, A a) {
out << "a=" << a << ",s=" << s;
return out;
}
But you probably should read about the rule of five notably this.

Related

Why does C++ allow nested namespace with same name? [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 3 years ago.
Improve this question
Codes bellowing compiles:
namespace x
{
namespace y
{
namespace x
{
struct C
{
C ()
{
std::cout << "x::y::z::C" << std::endl;
}
};
}
}
struct C
{
C ()
{
std::cout << "x::C" << std::endl;
}
};
}
x::C and x::y::x::C are not same, but it's sometimes confusing.
Why is x::y::x allowed in C++? Isn't it more clear to forbid this?
Why is x::y::x allowed in C++? Isn't it more clear to forbid this?
No offense, but I think your premise is seriously flawed.
Maybe you didn't notice but having names being the same on different levels of nesting is something very natural. Consider constructors. The fully qualified name of a constructor of class foo is foo::foo(). Nothing unusual is it?
Now what if I want to put my class inside a namespace called foo. I am not arguing that this is the best naming scheme, but from the top of my head I also see no reason to outright forbid it. The constructor would be foo::foo::foo() then.
Having a rule that would disallow such naming would lead to lots of frustration to anybody that wants to use such (possibly suboptimal, but thats just opinions) naming scheme while having absolutely zero gain for someone that does not want to use such naming. In total there would be no benefit.
It's similar to variables having the same name in different scopes. Technically valid. After all, at the assembly level there are no names, just pointers and sizes.
void foo()
{
int x = 1;
if (true)
{
int x = 2;
x = 3; // Whops
}
}
C++ is not a forgiving language, if you mess up with anything, including variables naming, you are on your own. If you want the language to save you, there are (plenty of) other languages to pick.
That said, MSVC (and probably other compilers) issues a warning when a declared variable hides another variable in an outer scope, so by reading compiler warnings you can be helped.

C++: Force separate instances of a class for code protection [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 5 years ago.
Improve this question
This may sound strange, but for purposes of obfuscation, I'm wondering if there's a way to create multiple instances of a class throughout my app, but instead of them all reusing the same underlying code, the compiler would create completely separate chunks of code for that class. Sort of an inline for a class.
This would need to work in Xcode and Visual Studio.
The reason for this, and in all fairness, this is an idea that I'm just playing with...I'm looking for another level to slow down a hacker from patching my license code. Typically, no matter how hard you try to prevent code hacking, there ends up being one place where your code returns something like a true/false....Is this license valid? And if a hacker finds that one spot, it's a simple patch. My idea is to try putting the license code, specially the same license class, all throughout my app...many of them...and check any one of them at any time. And if it's done well, the hacker might have to find 10 of them...not knowing that there's really something like 20 of them throughout my app. And all this would depend on writing one class, but it can't be the same piece of reused class code...they'd need to be all separate.
Any ideas?
Here is an attempt/proof of concept. I've drafted a class which has:
some garbage data based on a template argument, so it's harder to reuse data layout.
a method with side effect based on on a template argument, so it's harder to reuse the code
One should be aware that this is all tricky, because compiler is allowed to do any transformation on the code which preserves observable behaviour. Thus, just using a template with a param, would produce two distinct type language wise, but the code generated could be reused for both.
I am not sure whether an experienced hacker would draw any conclusions about the code, or even whether the license check code itself would be duplicated. It's possible. Below code shows that method has two occurences in which one is a loop and the other got unwound, see on godbolt assembly lines 108-113 and 134-142.
That being said, often optimization is a nice obfuscator. Maybe on times even better than hand-mangling.
This a way to start. Generally constexpr and templates are our friends in such cases, because they are processed at compile time, we need to ensure the generate unique things. One could probably try some constexpr hashing, etc.
Code:
#include <string>
#include <iostream>
using std::string;
using std::cout;
template<int N>
struct B {
constexpr B() : arr() {
for (auto i = 0; i != N; ++i)
arr[i] = i;
}
int arr[N];
};
template<int Randomizer = 42>
struct A{
string a{"data_a"}; // probably all member should be templated by Randomizer
B<Randomizer> padding;
string b{"data_b"};
void method() {
cout << a << "\n";
for(int i = 0; i<Randomizer; i++) {
cout << padding.arr[i]; // harmless side effect
}
cout << "\n" << b << "\n";
}
};
int main () {
A<> i1;
A<3> i2;
i1.method();
i2.method();
return 0;
}

Memory Efficient: Templates vs Basic data types [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 5 years ago.
Improve this question
Is the use of templates better than basic data types in terms of memory allocation and management?
Just in short:
templates - a way to write code once in a generic way, and in compilation time the compiler will generate code according to the template, if you used the templatic code.
example:
#include <iostream>
template<typename T>
T MultiplyByFive(T _val)
{
return _val * 5;
}
int main()
{
std::cout << MultiplyByFive(5) << " " << MultiplyByFive(5.5) << std::endl;
return 0;
}
In this example, the compiler will generate two MultiplyByFive functions. One for integer and one for double. The output will therefore be:
25 27.5
That's because these functions have been called. Now we have two function in the code (generated by the compiler)
int MultiplyByFive(int _val)
{
return _val * 5;
}
double MultiplyByFive(double _val)
{
return _val * 5;
}
We didn't code them directly, but the compiler did according to our template.
Memory allocation has little to do with template. Dynamic memory allocation is determined in run time (in c++ by the new operator). Static and local variable are determined in compile time, but it has nothing to do with generating code.
If I didn't understand the question, you're more then welcome to clarify.

Is it possible to create new type variable without struct? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 5 years ago.
Improve this question
Here is what i got but when i check type it displays "struct MyVarName"
#include <iostream>
#include <typeinfo>
typedef struct { char text[15];} MyVarName;
int g = 0;
int main(void) {
MyVarName a = { "super" };
std::cout << typeid(a).name() << '\n';
std::cout << typeid(g).name() << '\n';
return 0;
}
Is it possible to define your own variable type and then use it as any other variable?
Print, assign new value.. etc.
The result of std::type_info::name() is implementation-defined and could be anything, including a mangled name, the empty string, or a recipe for lasagna.
For example, GCC gives:
9MyVarName
i
Apparently yours is taking a C-like approach and calling it struct MyVarName, which is what you'd have to write to reference the type in C.
Simply don't rely on it for this kind of thing. C++ does not pretend to have meaningful reflection.
Besides that, there is nothing wrong with your code. You did define a new type. There are ways to introduce new types that don't require the creation of a class type (i.e. with struct or class), but these all involve aliasing existing types with typedef or using, and are thus limited. They won't allow you to create a complex type like std::string.
in C:
typedef char newtype[20];
void foo(void)
{
newtype a;
}

Strange GCC optimisation bug [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question appears to be off-topic because it lacks sufficient information to diagnose the problem. Describe your problem in more detail or include a minimal example in the question itself.
Closed 9 years ago.
Improve this question
I'm writing a fairly large application containing many different modules. I've always been programming with the GCC debugging info turned on and all optimisations turned off, for obvious reasons of debugging. Now I've decided that it's time for a release and I've set GCC to optimise to the best of it's abilities (-O3). And this is when the strangest of bugs appeared. Take the following code:
void SomeClass::setValue(int i) { this->iValue = i; }
int SomeClass::getValue() const { return this->iValue; }
Now without optimisations, these work perfectly. With optimisations, the value of SomeClass.iValue is not modified in the setValue() method. In fact, the output of the following:
cout << x.getValue();
x.setValue(5);
cout << x.getValue();
returns
0
0
when the iValue is intialised in the class to 0.
Now the strange part: if I insert the following code into setValue():
void SomeClass::setValue(int i) { cout << "Narf"; this->iValue = i; }
the code works!
Can someone please explain to me what is going on?
did you try checking cout<<x.iValue; ? perhaps the problem is in SomeClass::getValue(); for example, it returning void or being const ? :)
also, just an idea, the optimisation might happen in cout not your actual code as hinted by cout << "Narf";
Firstly, your code is not exactly correct. Getter function should return int instead of void. I think you just typed it incorrectly here, because gcc will not let you compile that (std::cout has no overloaded operator << for type void). What is more, SomeClass.i_value doesn't compile either. Did you mean this->i_value or just i_value?