reinterpret_cast memory not modified - c++

I tried to modify an object of A indirectly by allocating 8 bytes using std::allocator. I used <int> specifically, hoping it will return aligned memory for 2 integers. Then I modified an object of A.
Why do I only see A.x=9 in the bitset (towards the end 1001), what happened to A.y=10? Do I need to align the raw pointer returned by std::allocator?
I was expecting the output below:
0000000000000000000000000000100100000000000000000000000000001010
before=0000000000000000000000000000000000000000000000000000000000000000
---------------------
sizeof(A)=8
alignof(A)=4
x: 9 y: 10
---------------------
x: 9 y: 10
after=0000000000000000000000000000000000000000000000000000000000001001
#include <bitset>
#include <iostream>
struct A {
int x;
int y;
A() = delete;
friend std::ostream &operator<<(std::ostream &os, const A &a) {
os << "x: " << a.x << " y: " << a.y;
return os;
}
};
int main(int argc, char **argv) {
std::allocator<int> alloc;
auto raw = alloc.allocate(2);
std::bitset<64> before(*raw);
before.reset();
std::cout << "before=" << before << "\n";
std::cout << "---------------------\n";
std::cout << "sizeof(A)=" << sizeof(A) << "\n";
std::cout << "alignof(A)=" << alignof(A) << "\n";
auto a = reinterpret_cast<A *>(raw);
a->x = 9;
a->y = 10;
std::cout << *a << "\n";
std::cout << "---------------------\n";
std::bitset<64> after(*raw);
std::cout << *a << "\n";
std::cout << "after=" << after << "\n";
return 0;
}

I actually don't see any undefined behviour here.
The actual problem is that you seem to assume that before(*raw) creates a bitset with a snapshot of that memory region. But that is not what happens.
See: https://en.cppreference.com/w/cpp/utility/bitset/bitset
(you call the unsigned long long constructor)
If you simply write (before after):
unsigned long long raw_converted_to_long = *raw;
You see the value is 9 - this is the reason why the bitset is filled with 9.

Related

What Happens To Dynamically Allocated Variables Without Handles ? (C++)

Does instantiating classes without handles like this cause memory leaks in C++?
new SomeClass();
What about passing them inside methods?
SomeMethod(new SomeClass())
Do they get deallocated after the method's definition goes out of scope?
It does sound like a stupid question, but as far as I know, they're not going anywhere if they aren't freed.
Yes, you are correct. In default C++, every new call must be followed by a delete, otherwise it is a leak. However there are edge cases where new can be used without a delete.
One such case is with placement new where memory allocation is handled by yourself. Example:
#include <cstdint>
#include <memory>
#include <iostream>
struct X {
int a;
int b;
};
int main(int argc, char** argv) {
char buffer[256];
X* x1 = new (&buffer[0]) X{1,2};
X* x2 = new (&buffer[8]) X{3,4};
std::cout << "x1: " << x1->a << " " << x1->b << std::endl;
std::cout << "x2: " << x2->a << " " << x2->b << std::endl;
// no leaks since the memory is released when `buffer` is
// deallocated. However it is good practice to call the
// destructor directly
x1->~X();
x2->~X();
}
Produces:
Program stdout
x1: 1 2
x2: 3 4
Godbolt: https://godbolt.org/z/sEPWadcKh
Another case is when a class overrides the operator new as in this example:
#include <cstdint>
#include <memory>
#include <iostream>
static char buffer[32768];
static char* ptr = &buffer[0];
struct X {
int a;
int b;
void* operator new(size_t size) {
void* p = ptr;
ptr += size;
return p;
}
void operator delete(void*) {
// no need to do anything
}
};
int main(int argc, char** argv) {
X* x1 = new X{1,2};
X* x2 = new X{3,4};
std::cout << "x1: " << x1->a << " " << x1->b << std::endl;
std::cout << "xs: " << x2->a << " " << x2->b << std::endl;
// no leaks since the memory is released when `buffer` is
// deallocated. However it is good practice to call the
// destructor directly
x1->~X();
x2->~X();
}
Produces:
Program stdout
x1: 1 2
x2: 3 4
Godbolt: https://godbolt.org/z/jc4r9qbxh
Yet another case is when you use new with smart pointers like in the case below
#include <cstdint>
#include <memory>
#include <iostream>
#include <boost/intrusive_ptr.hpp>
struct X {
X(int a_, int b_ ) : a(a_), b(b_){
std::cout << "Constructor " << this << std::endl;
}
~X() {
std::cout << "Destructor " << this << std::endl;
}
int a;
int b;
int count = 0;
};
void intrusive_ptr_add_ref(X* x)
{
++x->count;
}
void intrusive_ptr_release(X* x)
{
if (--x->count == 0)
delete x;
}
int main(int argc, char** argv) {
boost::intrusive_ptr<X> x1 = new X{1,2};
boost::intrusive_ptr<X> x2 = new X{3,4};
std::cout << "x1: " << x1->a << " " << x1->b << std::endl;
std::cout << "x2: " << x2->a << " " << x2->b << std::endl;
}
Produces:
Constructor 0xb4b2b0
Constructor 0xb4c2e0
x1: 1 2
x2: 3 4
Destructor 0xb4c2e0
Destructor 0xb4b2b0
Godbolt: https://godbolt.org/z/b7MTfazT9
So although delete is called on your behalf, you as in the user does not have to call delete yourself.
Yet another use case is when creating objects for frameworks that manage the lifetime of objects like Qt.
So the answer is really YES, always call delete after new but there are plenty of cases in the industry where it is not really necessary.

How can I build a proper constructor and destructor?

Question #1: How can I build a constructor set the value for (R,PoF,PoR)? I am trying to understand how constructor works but I guess I don't quite get it.
Question #2: Can I build destructor in this way, instead of the way I used in my program?
Circle::~Circle()
{
std::cout << "The fence would cost " << SwimmingPool.PerimeterP(r) << std::endl;
std::cout << "The road would cost " << SwimmingPool.AreaP(r) << std::endl;
std::cout << "Present by FF" << std::endl;
}
I just want the cost to come out by itself, but I don't know how should I create destructor to do so.
Here is my full code:
#include "stdafx.h"
#include "iostream"
const double PI = 3.1415926;
class Circle
{
public:
Circle();
double AreaP(int r);
double PerimeterP(int r);
~Circle();
private:
int R;
int PoF;
int PoR;
};
double Circle::AreaP(int r)
{
return ((r + R)*(r + R) - r*r)*PI*PoR;
}
double Circle::PerimeterP(int r)
{
return (r + R) * 2 * PI*PoF;
}
Circle::Circle()
{
int R = 3;
int PoF = 35;
int PoR = 20;
}
Circle::~Circle()
{
std::cout << "Present by FF" << std::endl;
}
int main()
{
int r;
Circle SwimmingPool;
std::cout << "Please input the radius of the Swimming Pool." << std::endl;
std::cin >> r;
std::cout << "The fence would cost " << SwimmingPool.PerimeterP(r) << std::endl;
std::cout << "The road would cost " << SwimmingPool.AreaP(r) << std::endl;
return 0;
}
You have:
Circle::Circle()
{
int R = 3;
int PoF = 35;
int PoR = 20;
}
That function creates three function local variables and sets their values. It does not initialize the members of the class. Change it to:
Circle::Circle() : R(30), PoF(35), PoR(20) {}
Always prefer to initialize in the initializer list instead of setting the values in the body of the constructor.
No, you may not use:
Circle::~Circle()
{
std::cout << "The fence would cost " << SwimmingPool.PerimeterP(r) << std::endl;
std::cout << "The road would cost " << SwimmingPool.AreaP(r) << std::endl;
std::cout << "Present by FF" << std::endl;
}
SwimmingPool is a variable in main. It cannot be used in the destructor. Besides, it does not make sense to print those messages in the destructor. It should simply be
Circle::~Circle()
{
}
Circle::Circle() : R(3), PoF(3), PoR(3) {};
Define the R, PoF, PoR as const int
The destructor must not throw an exception and generally you want it to release resources acquired by the object. Usually not the best place to be outputting stuff to stdout.
Don't use std::endl unless you want to flush the stream. Use '\n' instead.

Why Would reinterpret_cast<const char*> of a Class and of Its Pre-Initialized Member Int Be the Same While Any Other Type of Variable Isnt?

I got this from an online exam (http://www.interqiew.com/tests?type=cpp) and have been stumped for some time.
I just don't get it. It compiles and runs fine. I've modified the code to be more expressive of the weirdness.
CODE:
#include <cstddef>
#include <iostream>
class A{
public:
A( ) : m_x( 3 ) { };
static ptrdiff_t member_offsetA(const A &a){
const char *p = reinterpret_cast<const char*>(&a);
const char *q = reinterpret_cast<const char*>(&a.m_x);
const char *z = reinterpret_cast<const char*>(&a.m_y);
const char *s = reinterpret_cast<const char*>(&a.m_s);
std::cout << q << " VS " << p << " VS " << z << " VS " << s << std::endl << std::endl;
return p-q;
}
static ptrdiff_t member_offsetB(const A &a){
const char *p = reinterpret_cast<const char*>(&a);
const char *q = reinterpret_cast<const char*>(&a.m_x);
const char *z = reinterpret_cast<const char*>(&a.m_y);
const char *s = reinterpret_cast<const char*>(&a.m_s);
std::cout << q << " VS " << p << " VS " << z << " VS " << s << std::endl << std::endl;
return z-s;
}
static ptrdiff_t member_offsetC(const A &a){
const char *p = reinterpret_cast<const char*>(&a);
const char *q = reinterpret_cast<const char*>(&a.m_x);
const char *z = reinterpret_cast<const char*>(&a.m_c);
std::cout << q << " VS " << q << std::endl << " VS " << z << std::endl;
return q-z;
}
private:
int m_x;
int m_c;
char m_y;
std::string m_s;
};
int main(){
A a;
std::cout << ( ( A::member_offsetA( a ) == 0 ) ? 0 : 1 ) << std::endl;
std::cout << ( ( A::member_offsetB( a ) == 0 ) ? 2 : 3 ) << std::endl;
std::cout << ( ( A::member_offsetC( a ) == 0 ) ? 4 : 5 ) << std::endl;
return 0;
}
OUTPUT: Symbols will be represented by unique letters preceded by three X's. So all XXXS's represent the same symbol. Whitespace means nothing was printed there.
XXXA VS XXXA VS VS XXXB
0
XXXA VS XXXA VS VS XXXB
3
XXXA VS XXXA
VS XXXF
5
How does any of this make sense?
Why would the casting for a class and a member int produce the same results? Wouldn't they be different? If they're the same, why would other member values be different?
Also, why would anyone ever use this?
P.S. Paste of actual output:
VS VS �# VS �����
0
VS VS �# VS �����
3
VS
VS �
5
I don't see anything strange here. It makes perfect sense.
For normal, non-polymorphic classes the address of an instance of a class will be the same as the address of the first member of that class. That's just what an instance of a class is; it's the sum of all its members laid out sequentially (the instance itself adds nothing, unless it's a polymorphic class, or has non-empty base classes.) This is (not exactly but almost) called an "standard-layout" class in C++ (Note: the actual definition is obviously more complex.)
In the case of the members inside a class (and in fact for all variables,) no two of them can have the same address. And in fact they need 1 or more bytes of memory (you know, to store the bits of their respective values inside them.) So it again makes perfect sense for the addresses for consecutive members be different.
You might want to check out this code (which I believe is more instructive):
(Note: beware that there is "undefined behavior" in my particular use of pointer arithmetic here, so this in not completely correct C++. But to my knowledge it works fine. It's here for demonstration purposes anyways, so don't use this in production!)
#include <cstddef>
#include <iostream>
#include <string>
template <typename T, typename U>
ptrdiff_t Dist (T const * from, U const * to) {
return reinterpret_cast<char const *>(to) - reinterpret_cast<char const *>(from);
}
class A{
public:
A( ) : m_x( 3 ) { };
void printOffsetsAndSizes () const {
std::cout << "A: " << reinterpret_cast<uintptr_t>(this) << " (" << sizeof(*this) << ")" << std::endl;
std::cout << " m_x: " << Dist(this, &m_x) << " (" << sizeof(m_x) << ")" << std::endl;
std::cout << " m_c: " << Dist(this, &m_c) << " (" << sizeof(m_c) << ")" << std::endl;
std::cout << " m_y: " << Dist(this, &m_y) << " (" << sizeof(m_y) << ")" << std::endl;
std::cout << " m_s: " << Dist(this, &m_s) << " (" << sizeof(m_s) << ")" << std::endl;
}
private:
int m_x;
int m_c;
char m_y;
std::string m_s;
};
int main () {
A a;
a.printOffsetsAndSizes ();
return 0;
}
which gives this output on Ideone:
A: 3213332880 (16)
m_x: 0 (4)
m_c: 4 (4)
m_y: 8 (1)
m_s: 12 (4)

Handing over std::vector to function with pointer

I have been searching on Google an in this forum for a while, but I could not find any answer or tip for my problem. Tutorials couldn't help me either...
I want to redistribute some points, stored in a vector p_org. (x-value is stored as double).
Therefore I have the function distribute, which is defined in maths.h
distribute_tanh(&p_org_temp,&p_new_temp,iz,spacing[0],spacing[1],l_rot[(kk+1)*iz-2],status);
The function distribute_tanh does look like this:
inline void distribute_tanh (std::vector<double> *p_org, std::vector<double> *p_new, const int n_points, double spacing_begin, double spacing_end, const double total_length, double status){
//if status == 0: FLAP, if status == 1: SLAT
std::cout << "spacing_begin: " << spacing_begin << " spacing_end: " << spacing_end << std::endl;
double s_begin = spacing_begin / total_length;
double s_end = spacing_end / total_length;
double A = sqrt(s_end/s_begin);
double B = 1 / (sqrt(s_end*s_begin)*n_points);
std::cout << "A: " << A << " B: " << B << std::endl;
std::vector<double> u (n_points);
std::vector<double> sn (n_points);
double dx;
double dy;
std::cout << "Control at the beginning: p_org: " << (p_org) << " p_new: " << (p_new) << " n_points: " << n_points << " s_begin: " << s_begin << " s_end: " << s_end << " total_length: " << total_length << std::endl;
//problem no. 1
for (int i=0;i<n_points;i++){
if (B > 1.001) {
if (B < 2.7829681) {
double Bq=B-1;
dy=sqrt(6*Bq)*(1-0.15*Bq+0.057321429*pow(Bq,2)-0.024907295*pow(Bq,3)+0.0077424461*pow(Bq,4)-0.0010794123*pow(Bq,5));
} else if (B > 2.7829681) {
double Bv=log(B);
double Bw=1/B-0.028527431;
dy=Bv+(1+1/Bv)*log(2*Bv)-0.02041793+0.24902722*Bw+1.9496443*pow(Bw,2)-2.6294547*pow(Bw,3)+8.56795911*pow(Bw,4);
}
u[i]=0.5+(tanh(dy*(i*(1.0/n_points)-0.5))/(2*tanh(dy/2)));
}
else if (B < 0.999) {
if (B < 0.26938972) {
dx=M_PI*(1-B+pow(B,2)-(1+(pow(M_PI,2))/6)*pow(B,3)+6.794732*pow(B,4)-13.205501*pow(B,5)+11.726095*pow(B,6));
} else if (B > 0.26938972) {
double Bq=1-B;
dx=sqrt(6*Bq)*(1+0.15*Bq+0.057321429*pow(Bq,2)+0.048774238*pow(Bq,3)-0.053337753*pow(Bq,4)+0.075845134*pow(Bq,5));
}
u[i]=0.5+(tan(dx*(i*(1.0/n_points)-0.5))/(2*tan(dx/2)));
}
else {
u[i]=i*(1.0/n_points)*(1+2*(B-1)*(i*(1.0/n_points)-0.5)*(1-i*(1.0/n_points)));
}
sn[i]=u[i]/(A+(1.0-A)*u[i]);
std::cout << "sn(i): " << sn[i] << std::endl;
std::cout << "p_org[n_points]: " << &p_org[n_points-1] << std::endl;
if(status==0){
//p_new[i]=p_org[0]+(total_length*sn[i]);
std::cout << "FLAP maths.h" << std::endl;
}
//Here is the problem no. 2
else if(status==1){
//p_new[i]=p_org[0]-(total_length*sn[i]);
std::cout << "SLAT maths.h" << std::endl;
}
//std::cout << "p_new in math: " << p_new << std::endl;
}
}
My problem is, that I am unable to access the value of p_org or p_new. At the beginning I would like to give out the value of p_org and p_new. If I try it with a *, the compiler is complaining: error: no operator "<<" matches these operands
operand types are: std::basic_ostream> << std::vector>
std::cout << "Control at the beginning: p_org: " << (*p_org) << " p_new: " << (*p_new) << " n_points: " << n_points << " s_begin: " << s_begin << " s_end: " << s_end << " total_length: " << total_length << std::endl;
If I leave the * off, I get the addresses of p_org and p_new.
At the end of the code I would like to write the new value to p_new. If I use * to access the value, the compiler is complaining, if I leave it off, its complaining too with the following message:
error: no operator "-" matches these operands
operand types are: std::vector<double, std::allocator<double>> - double
p_new[i]=p_org[0]-(total_length*sn[i]);
^
I tried to understand both problems, but until now I had no success.
Thanks for your advice.
Your issue with the compiler error can be cut down to a very simple program.
#include <vector>
void foo(std::vector<int>* pV)
{
pV[0] = 10; // error.
}
int main()
{
std::vector<int> v(10);
foo(&v);
}
The issue is that operator[] as done above works for objects and references, not pointers. Since pv is a pointer, you must dereference it first to obtain the object, and then apply [] to the dereferenced pointer.
void foo(std::vector<int>* pV)
{
(*pV)[0] = 10; // No error
}
The other form of calling operator[] can be also used, but is a bit more verbose:
void foo(std::vector<int>* pV)
{
pv->operator[](0) = 10; // No error
}
However, to alleviate having to do this, pass the vector by reference. Then the "normal" way of using operator[] can be used.
#include <vector>
void foo(std::vector<int>& pV)
{
pV[0] = 10; // No error.
}
int main()
{
std::vector<int> v(10);
foo(v);
}

Address of function pointers in C++ [duplicate]

This question already has answers here:
How to print function pointers with cout?
(7 answers)
Closed 9 years ago.
I'm not clear on what the values that are being returning from calling:
&next, fp, *fp, &return_func_ptr, fp_ptr, &fp_ptr, *fp_ptr
They all seem to give me the value 1. What does it mean?
Also, how would I declare
int (*return_f())(char)
to receive a parameter without using typedef?
#include <iostream>
int next(int n){
return n+99;
}
// returns pointer to a function
typedef int (*fptr)(int); // using typdef
fptr return_func_ptr(){
return next;
}
int f(char){
return 0;
}
int (*return_f())(char){ // how do you pass a parameter here?
// std::cout << "do something with " << param << std::endl;
return f;
}
int main()
{
int x = 5;
// p points to x
int *p = &x;
std::cout << "x=" << x << std::endl; // 5, value of x
std::cout << "&x=" << &x << std::endl; // 0x7fff6447a82c, address of x
std::cout << "p=" << p << std::endl; // 0x7fff6447a82c, value of p is address of x
std::cout << "*p=" << *p << std::endl; // 5, value of x (p dereferenced)
std::cout << "&p=" << &p << std::endl; // 0x7fff6447a820, address of p pointer
// change value of x thru p
// p = 6; // error, can't set int* to int
*p = 6;
std::cout << "x=" << x << std::endl; // 6
int y = 2;
// int *q = y; // error can't initiate with type int, needs int*
// pointer to a function
int (*fp)(int);
std::cout << "&fp=" << &fp << std::endl; // 0x7fff66da6810, address of pointer fp
std::cout << "fp=" << fp << std::endl; // 0, value of pointer fp
fp = &next; // fp points to function next(int)
fp = next;
std::cout << "&next=" << &next << std::endl; // 1, address of function?
std::cout << "fp=" << fp << std::endl; // 1, value is address of function?
std::cout << "&fp=" << &fp << std::endl; // 0x7fff66da6810, address of pointer fp?
std::cout << "*fp=" << *fp << std::endl; // 1, address of function?
// calling function thru pointer
int i = 0;
i = (*fp)(i);
std::cout << "i=" << i << std::endl; // 99
i = fp(i);
std::cout << "i=" << i << std::endl; // 198
// function returns pointer to function
fptr fp_ptr = return_func_ptr();
std::cout << "&return_func_ptr=" << &return_func_ptr << std::endl; // 1
std::cout << "fp_ptr=" << *fp_ptr << std::endl; // 1
std::cout << "&fp_ptr=" << *fp_ptr << std::endl; // 1
std::cout << "*fp_ptr=" << *fp_ptr << std::endl; // 1
int j = fp_ptr(1);
std::cout << "j=" << j << std::endl; // 100
}
There is some pointer here who seems not clear :
// pointer to a function
int (*fp)(int);
std::cout << "&fp=" << &fp << std::endl; // 0x7fff66da6810, address of pointer fp
std::cout << "fp=" << fp << std::endl; // 0, value of pointer fp
Here fp is undefined. Those lines have an undefined behaviour.
After that :
// function returns pointer to function
fptr fp_ptr = return_func_ptr();
std::cout << "&return_func_ptr=" << &return_func_ptr << std::endl; // 1
std::cout << "fp_ptr=" << *fp_ptr << std::endl; // 1
std::cout << "&fp_ptr=" << *fp_ptr << std::endl; // 1
// ^^^^^^^^^^ ^^^^^^^
std::cout << "*fp_ptr=" << *fp_ptr << std::endl; // 1
There are two things here :
On the line I pointed, I'm not sure it is what you wanted to test.
Also, cout doesn't have an overload to take a function pointer, it will take a bool instead. So it should be :
std::cout << "fn_ptr=" << reinterpret_cast<void*>( fn_ptr ) << std::endl;
I would suggest you to read this article about function pointer, it explains almost all you need to know : http://www.learncpp.com/cpp-tutorial/78-function-pointers/
std::cout << "fp_ptr=" << *fp_ptr << std::endl;
should be
std::cout << "fp_ptr=" << (void*)fp_ptr << std::endl;
The cout operator doesn't have an overload for a function pointer, so it uses bool instead. That's why you always get 1 as output. When I compile your code, I even get a warning for that, telling me that it will always evaluate to true. You should switch on all warnings and try to get rid of them.