Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ pointers memory usage

Keep going around circles, but I am still unclear about this. Have a feeling about the answer; but not sure. Which code below consumes more memory? [Should be the former, if I am correct.]

double x;
double* y = new double(x);

OR

double x;
double* y = &x;
like image 716
squashed.bugaboo Avatar asked Dec 01 '25 05:12

squashed.bugaboo


2 Answers

In the former, two doubles exist (x, and the one pointed to by y). x is allocated on the stack, and y on the heap.

In the latter, only one double exists (x, also pointed to by y). There are no heap allocations involved here.

So, on the face of it, you are correct.

In both cases, there exists one double on the stack, and one double* also on the stack. The difference between the two is that in the first case, there is also a double allocated on the heap (the one allocated by new double(x)). Therefore the first case requires more storage.

like image 117
Graham Borland Avatar answered Dec 03 '25 21:12

Graham Borland


The following consumes sizeof( double ) + sizeof( double* ) plus sizeof( double ) on the heap:

double x;
double* y = new double(x);

The following consumes sizeof( double ) + sizeof( double* ):

double x;
double* y = &x;
like image 28
Konrad Avatar answered Dec 03 '25 20:12

Konrad



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!