Why does same pointer has different addresses - c++

class A{};
void Foo(A *p)
{
std::cout << &p << std::endl;
std::cout << p << std::endl;
}
int main()
{
A *p = new A();
std::cout << &p << std::endl;
std::cout << p << std::endl;
Foo(p);
}
The above program prints the same value for p but different addresses for &p. Can somebody please explain why ?

The above program prints the same value for "p"
This is because one p is a copy of the other, so they both have the same value. The value of a pointer is a memory address where an object is stored so having the same value means pointing to the same object.
A function argument is a copy of the object that was passed to the function †.
but different addresses for "&p". Can somebody please explain why ?
Each p here is a separate variable and a separate object ††. Both objects exist simultaneously. The C++ standard specifies that each currently existing object has a unique address †††, so therefore each p here must have a unique address.
The Unary operator & is the addressof operator, and it returns the memory address where the operand is stored.
† Unless that function argument is a reference. In that case the reference is bound to the passed object. The p argument is not a reference.
†† Pointers themselves are objects. The memory address where a pointer stored is separate from the memory address that is its value which is the memory address of the pointed object.
††† There are exceptions in case of sub-objects, but those exceptions aren't relevant here.

void Foo(A *p)
{
std::cout << &p << std::endl;
std::cout << p << std::endl;
}
When you pass something to Foo() that something is copied into p.So the actual parameter(the something which was passed) is not the same thing as the formal parameter(p here), though they will hold the same value.
Inside Foo(), &p will print address of this formal parameter and not the address of the actual parameter that was passed.
And since the formal and actual parameter hold same value, p prints the same value.

operator & is returns Address of Variable
They are difference variable A *a and Foo(A *a) but they pointing to the same address. It's normally has difference address.

Here is a good description of stack and heap.
What and where are the stack and heap?
A short answer as others have mentioned is that:
p points to the allocated instance of A which is allocated from the heap. It is created with the operator 'new' in your code.
&p is pointing to the memory which p itself occupies.
Just as class A occupies memory (which is allocated from the heap using the 'new' operator) p occupies memory (allocated from the stack since it is a local variable).

this event occures because of copy constructors.
The copy constructor is a constructor which creates an object by initializing it with an object of the same class, which has been created previously. The copy constructor is used to −
-Initialize one object from another of the same type.
-Copy an object to pass it as an argument to a function.(this refer to your problem)
-Copy an object to return it from a function.
p is local variable that contain address of object in heap . and &p is address of p in stack. when we pass p to Foo() because of copy constructor
compiler copy p to new local variable hence we have 2 pointer that both of them refer to same location in heap memory. on of them is original p(actual parameter) and second is unnamed local variable(Formal Parameter) in Foo() method that has been built by copy constructor.
also you could see difference between p an &p in below image.

Related

Different address of std::unique_ptr::get and operator&

Using pointers in the example below gave me a confusion so I probably misunderstand something. I will try to show my way of understanding and some pseudo-simple example.
Creating std::unique_ptr variable of name my_int ensures that it can not be copied and there is only one owner of it's int object. Then I create a vector to storage the pointer and put it without copying with std::emplace_back().
Now I would like to check if the element of vector integers[0] has the same address in memory as the orginal element my_int. I thought it should because this element could not be copied.
Example code:
auto my_int = std::make_unique<int>(1);
std::vector<std::unique_ptr<int>> integers;
integers.emplace_back(my_int.get());
std::cout<< "Value of my_int: " << *my_int << std::endl;
std::cout << "Address of my_int: " << my_int.get() << std::endl;
std::cout << "Also address of my_int: " << &my_int << std::endl;
std::cout << "Also address of my_int: " << &integers[0]<< std::endl;
std::cout << "Also address of my_int: " << integers[0].get()<< std::endl;
Result of test:
Value of my_int: 1
Address of my_int: 0x260fc40
Also address of my_int: 0x65fb58
Also address of my_int: 0x260fe20
Also address of my_int: 0x260fc40
I also tried using std::move() when putting the object to vector but the effect is the same, addresses differs but I don't understand why.
My first confusion is that &my_int and my_int.get() is not the same and the second confusion is that also integers[0].get() differs from &integers[0].
The expression my_int.get() returns a pointer to the contained integer, its type is int*.
The expression &my_int returns a pointer to the my_int object itself, and has the type std::unique_ptr<int>*.
And integers[0] is a distinct and different object from my_int. They just happen to contain the same pointer. This is bad for a unique pointer: together, they will try to free the same memory twice. You must use std::move
auto my_int = std::make_unique<int>(1);
std::vector<std::unique_ptr<int>> integers;
integers.emplace_back(std::move(my_int)); // push_back also works
This way my_int will be set to contain nullptr, and only integers[0] will contain the pointer to the allocated memory.
To understand my_int (or pointers in general really) better you might think of it something like this:
+--------+ +---+
| my_int | --> | 1 |
+--------+ +---+
^ ^
| |
&my_int my_int.get()
It's the same thing with integers[0].get() and &integers[0].
Creating std::unique_ptr variable of name my_int ensures that it can not be copied and there is only one owner of it's int object.
It is only the std::unique_ptr that cannot be copied. But unique pointer cannot guarantee that you won't copy the bare pointer that it owns. Copying the bare pointer owned by the unique pointer is what exactly you did which results in two "unique" owners of the same resource. And that will result in undefined behaviour when the second unique pointer is destroyed.
When you call std::unique_ptr::get, the unique pointer won't release its ownership to you. You should never pass a pointer, that isn't owned by you, into constructor of a smart pointer.
To fix this, you can transfer the ownership from one smart pointer into another by move:
integers.emplace_back(std::move(my_int));
addresses differs but I don't understand why.
The unique pointer variable is one object, and the element of the vector is another object. Since they are separate objects, they have a separate address. Even if they happen to be pointers that point to the same object - the integer, which is yet another object. Those three objects correspond to the three different addresses that you see in the output.

pointers scope questions and return reference of pointer inside vector of pointers encapsulated in class

I have some questions about pointers, scopes and pointers inside vector encapsulated in class
i have this supposed cases and examples with questions:
Example 1
the variable int y scope is inside the function and when the function finish and go away that returning reference will be died and that reference be referenced to nothing?
int& createInt() {
int y = 5;
return y;
}
case1: if i do this in main or other function:
int x = createInt();
std::cout << "x value \n";
std::cout << x << "\n";
// std::cout return 5
this mean that im saving my own copy of the value of createInt()
function that is 5 in the variable x, so is safe because int x contain their own value?
but what happen with the reference returning from the createInt() function, is there a memory leak or not because is not a pointer a will die with the scope of the function.
case 2: if i do this in main or other function:
int &x = createInt();
std::cout << "x value \n";
std::cout << x << "\n";
// std::cout return 32767
int &x is equals to the reference returning from createInt() function, that reference die when the function finish/go away so for that reason
int &x is returning a wrong value 32767 and not 5 or what are that 32767 value?
so int &x = createInt(); is evil and very bad practice because is reference to nothing.
example 2
what about this? i'm requesting allocation memory for int and initialized memory to the pointer variable...
int& createInt() {
int* y = new int(5);
return *y;
}
that pointer variable is in the stack but store a reference to the new int that is in the heap, so that new int will be alive when the scope of the function go away because is in the heap right?
so when i return the reference i'm returning the reference to that new int not the pointer variable, right? so is bad to returning the reference instead of the pointer? for what?
case1: if i do this in main or other function:
int x = createInt();
std::cout << "x value \n";
std::cout << x << "\n";
// std::cout return 5
i'm creating a copy of the new int value from createInt() in my local int x variable, so is this a memory leak because i'm creating a copy and not getting the pointer, so i can't do a delete of int x variable because is not a pointer, and also i can't delete the int *y pointer created inside createInt() function because the pointer is lost, i don't have it outside the createInt()
but whats happen if i do:
delete &x;
i will get a error:
malloc: *** error for object 0x7ffee204b8c8: pointer being freed was not allocated
because i'm deleting my int x that is not in the heap? or is trying to delete the int *y inside the createInt() function ?
case2: if i do this with the same function:
int &x = createInt2();
std::cout << "x value \n";
std::cout << x << "\n";
// std::cout return 5
my int &x is a reference of the returning by createInt()
so i can do:
delete &x;
is a memory leak here? but its so bad delete &x reference instead of the pointer int *y? maybe doing delete & i'm not have form to be sure if that is allocated memory or is stack memory, so good practice is never try to delete using &?
vectors parts:
i have a class A that contain a vector of pointers of class B, also i have a method that return a element of the vector but as reference (because i want to have it in memory to reutilize it and control when is deleted like a connection pool also i move it from used vector to notInUsevector but this is other history), and in the destructor of class A i delete all the vector elements:
Class A {
//this is singleton
public:
static A& getInstance()
{
std::call_once(m_once, []() {
instance.reset(new Database());
});
return *instance;
}
B& getFirstElement() {
auto element = connections.front();
return *element;
}
~A() {
for(auto element : myVector){
delete num;
}
}
A(A const &) = delete;
void operator=(A const &) = delete;
private:
A();
static std::unique_ptr<A> instance;
static std::once_flag m_once;
std::vector<B*> myVector;
}
so in other place/function/class etc i do:
auto element = &A::getInstance().getFirstElement();
or maybe is best or the same:
auto &element = A::getInstance().getFirstElement();
so when the Class A instance is deleted the destructor will delete all the pointers inside myVector
is this safe, there is a memory leak? it's a very bad return the reference in the getInstance() function instead of the pointer?
thanks
First of all let's make it clear, scope is "layer" between { and }. It might be a function body, statement (if, switch, for, etc.) or standalone scope. The most important consequence is that life time of objects created on stack is limited to that scope.
Take your function createInt() as example, internal int y, exists only inside of that function. The moment you reach } that memory is free.
Second thing is term memory leak. Memory leak is a situation where you have a chunk of memory (might be a single byte, might be a couple of pages) and no way to point at it. It's like a locked box without a key. It is there, it is yours memory, it won't be free unless you tell, problem is you don't know where that memory is located, you have no pointer for it.
That's being said, let's talk about your cases:
Example 1 Case 1:
You are lucky. Your function return its internal y by reference, but this returned variable is freed before you return from your function. Effectively you have a value written down on sticky note, then you throw it to the trash and then return saying that your value is on that note that is in trash. The only reason you can still read it is because no one assigned that bit of memory in the mean time and it was not overwritten. Remember, the moment your function reached } all stack alocated variables (y was allocated on stack) are destroyed. That also answer your second question about memory leak, there is no memory leak. As long as you work with stack, allocation and deallocation is done "automagically" as destructor calls are inserted at the end of the scope (usually) by compiler.
Example 1 Case 2:
The very same thing as in case 1. Your returned value is compromised because you returned stack allocated variable that is no longer valid as you return from function. Now you can observe this because between assigning and reading that value you make a function call. Depending on where original y was allocated that bit of memory might be reused during std::cout call. This become obvious as you work on the very same bit of memory cause of reference usage. Remember when you reached } of createInt(), you free that bit of memory. As an additional excersise, put a break point on lines int &x = createInt(); and int x = createInt(); then step into function and watch memory state as you leave it.
Example 2 Case 1:
Now you create (potential) memory leak. You allocate a memory on heap so it won't be destroyed as you leave function body. You also pass that exact memory address, so you also should take responsibility for freeing it and you don't call delete, so that's your memory leak. And one more problem occurs as you assign returned value to completely new stack allocated variable. Your original x from createInt() is allocated, then returned by reference but feed to assign operator to other independent variable (int x have different address than int* y). Again you can check this with help of breakpoints and debugger.
Example 2 Case 2:
Now this is almost proper use of variables returned by reference and assignment of them. You create variable x on heap, then return it's address and assign it to y. Problem being as x was created on stack you are responsible for destroying it so call to delete is neccessary to avoid memory leak. Put a break point and track memory addresses of both x and y. They are the same.
General rule of thumb is that return by reference should be used only with variables that exist outside of function, for example you can use it for class memebrs as they live inside the object or for global or static variables. For other purposes use return by value, unless you really need that very object, then return it by pointer. And while you work with pointers always be aware that someone at some point have to delete underlying variable.
I skip the part about vectors and instead point you a good tool for tracking memory leaks. It's not the best solution by any means, but for starters it will do the trick (assuming you are using Visual Studio).
https://learn.microsoft.com/pl-pl/visualstudio/debugger/finding-memory-leaks-using-the-crt-library?view=vs-2019
Remember to use breakpoints and debugger instead of printing everything to output/console. This will help you a lot. In both tracking memory and variable state, and understanding what your code really does.
I don't have the impression you have a real question at all, because you seem yo have found out all tricks, traps and good practices on your own. You seem to know about memory leaks and dangling references. Static and dynamic allocation. Most of your assumptions seem correct. Some hints though :
* references '&' and raw pointers result in exactly the same machine instructions, but they are hints to the programmers. Indeed, a method returning a reference likely means you don't have to take ownership for that reference, but without documentation there is no guarantee on the lifetime of that object. A raw pointer may represent a heap instance, or an optional argument, but it could also represent just a reference. This lack of ownership rules in C/C++ is indeed tricky.
* When dereferencing a dangling reference, the behavior is undefined. It may be working perfectly on your machine and it could burn my harddisk. Anything goes.
* When dealing with heap allocations, we nowadays prefer yo use smart pointers whenever possible. There is no mistaking in it's usage. Search for unique_ptr and shared_ptr
* Finally I recomy learning a bit of Rust. This is a programming language that was specifically designed to resolve such object lifetime/ownership issues. It is quite easy to install and run the most basic examples. Just try returning a dangling reference with Rust, you'll learn a lot, believe me.

C++ Different types of pointers

in the following code I found that same pointer instruction crash the application in a situation while not in other situation.
#include <iostream>
using namespace std;
int main()
{
int *p;
*p = 50; //this instruction causes the crash
int* q = new int;
*q = 50; //this instruction executes ok
cout << "p:" << p << endl;
cout << "q:" << q << endl;
return 0;
}
I want to know why this is the case?
The first pointer is uninitialized. It doesn't point to a memory location that has an int value. So when you deref it on the next line, you get a crash.
The second pointer is initialized to an int that has an actual space in memory. So when you deref it, it finds the value held in that space.
int *p;
This pointer points to nowhere i.e not at any valid address of the process. That's why it crashes
int* q = new int;
Points to a valid address returned by new int, hence worked
I see you need some links to documentation:
http://en.cppreference.com/w/cpp/language/pointer
http://en.cppreference.com/w/cpp/language/operator_member_access
http://en.cppreference.com/w/cpp/language/new
http://en.cppreference.com/w/cpp/language/delete
http://en.cppreference.com/w/cpp/language/storage_duration
To wrap it up:
You can use the indirection operator (*) to return the object the pointer points to (dereference the pointer).
You can only access (read or modify) an object via a pointer, when the pointer actually points to an object (which by default they don't).
You can assign the address of an object to the pointer to let the pointer point at it.
You can use the address-of operator (&) to acquire the address of an object for assigning it to a pointer.
You can use the new operator to create a new object and return the address to it for assigning it to a pointer.
You must use delete to eventually destroy objects created using new.
When you use pointers, you alone are responsible for the validity of the objects your pointers point to. Don't expect the compiler to warn you when objects are leaked or accessed beyond the end of their lifetime. If you do it wrong, you might observe undefined behavior.
Smart pointers can help to keep track of object ownership and take care of proper destruction.
For further reading:
Can a local variable's memory be accessed outside its scope?
What does "dereferencing" a pointer mean?
Undefined, unspecified and implementation-defined behavior
What is a smart pointer and when should I use one?
https://ericlavesson.blogspot.de/2013/03/c-ownership-semantics.html
https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#e6-use-raii-to-prevent-leaks

Organization of a c++ program in memory - stack and heap [duplicate]

This question already has answers here:
What and where are the stack and heap?
(31 answers)
Closed 8 years ago.
I am learning c++ and would like to know how a program like this is organized in primary-memory. I understand that there are a stack (with stackframes) and a heap. And I know that dynamically allocating something allocates it on the heap. This is done by operators like malloc or new. But I cant see them in this small c++ program.
The program consists of a main-class and a class named MyClass. This class has:
one constructor
one member variable (int)
one member-function
The main-class defines an object to Myclass and as well defines a pointer to this object.
SO - how are all this organized in memory?
#include <iostream>
using namespace std;
class MyClass {
int i;
public:
MyClass(int n) {
i = n;
}
int get_nmbr() {
return this->i;
}
};
int main() {
MyClass myClass(100), *p;
cout << myClass.get_nmbr() << endl;
p = &myClass;
cout << p;
return 0;
}
Let's go through this line by line.
int main() {
A new function starts with this line, and therewith a new scope.
MyClass myClass(100), *p;
Two things happen here. One, a variable myClass is declared within the function's scope, which makes it a local variable and thus it's allocated on the stack. The compiler will emit machine instructions that reserve enough space on the stack (usually by bumping the sp stack pointer register), and then a call to the class constructor executes. The this pointer passed to the constructor is the base of the stack allocation.
The second variable p is just a local pointer, and the compiler (depending on optimizations) may store this value on the local stack or in a register.
cout << myClass.get_nmbr() << endl;
Call the get_nmbr() method of the local myClass instance. Again, the this pointer points to the local stack frame allocation. This function finds the value of instance variable i and returns it to the caller. Note that, because the object is allocated on the stack frame, i lives on the stack frame as well.
p = &myClass;
Store the address of the myClass instance in variable p. This is a stack address.
cout << p;
return 0;
}
Print out the local variable p and return.
All of your code is only concerned with stack allocations. The result of that is that when the function's scope is left/closed at execution time (e.g. the function returns), the object will be automatically "destructed" and its memory freed. If there are pointers like p that you return from that function, you're looking at a dangling pointer, i.e. a pointer that points at an object that's freed and destructed. (The behavior of a memory access through such a dangling pointer is "undefined" as per language standard.)
If you want to allocate an object on the heap, and therefore expand its lifetime beyond the scope wherein it's declared, then you use the new operator in C++. Under the hood, new calls malloc and then calls an appropriate constructor.
You could extend your above example to something like the following:
{
MyClass stackObj(100); // Allocate an instance of MyClass on the function's stack frame
MyClass *heapObj = new MyClass(100); // Allocate an instance of MyClass from the process heap.
printf("stack = %p heap = %p\n", stackObj, heapObj);
// Scope closes, thus call the stackObj destructor, but no need to free stackObj memory as this is done automatically when the containing function returns.
delete heapObj; // Call heapObj destructor and free the heap allocation.
}
Note: You may want to take a look at placement new, and perhaps auto pointers and shared pointers in this context.
First things first. In C++ you should not use malloc.
In this program, all memory used is on the stack. Let's look at them one at a time:
MyClass myClass(100);
myClass is an automatic variable on the stack with a size equal to sizeof(MyClass);. This includes the member i.
MyClass *p;
p is an automatic variable on the stack which points to an instance of MyClass. Since it's not initialized it can point anywhere and should not be used. Its size is equal to sizeof(MyClass*); and it's probably (but not necessarily) placed on the stack immediately after myClass.
cout << myClass.get_nmbr() << endl;
MyClass::get_nmbr() returns a copy of the member i of the myClass instance. This copy is probably optimized away and therefore won't occupy any additional memory. If it did, it would be on the stack. The behavior of ostream& operator<< (int val); is implementation specific.
p = &myClass;
Here p is pointing to a valid MyClass instance, but since the instance already existed, nothing changes in the memory layout.
cout << p;
Outputs the address of myClass. Once again the behavior of operator<< is implementation specific.
This program (kind of) visualizes the layout of the automatic variables.
You have myClass object and pointer p (declared as MyClass *) created on stack. So. within myClass object the data members i also gets created on stack as part of myClass object. The pointer p is stored on stack, but you are not allocating for p, rather you are having p assigned to address of myClass object which is already stored on stack. So, no heap allocation here, at least from the program segment that you posted.
myClass is allocated on the stack. This program doesn't use heap exept maybe for allocating a stdout buffer behind the scenes. When myClass goes out of scope (e.g. when main returns or throws an exception), myClass is destructed and the stack is released, making p invalid.
In modern C++ it is considered safer to use smart pointers, such as the shared_ptr, instead of raw pointers.
To allocate myClass on the heap you could write:
#include <memory>
int main() {
std::shared_ptr<MyClass> p (new MyClass (100)); // Two heap allocations: for reference counter and for MyClass.
auto p2 = std::make_shared<MyClass> (101); // One heap allocation: reference counter and MyClass stored together.
return 0;
}

How does exactly this code work in C++

For example this code:
#include <iostream>
using namespace std;
void foo(int* x){ cout << "X = " << *x << endl;}
int main()
{
int value = 5;
int *p = &value;
foo(p);
foo(&value);
return 0;
}
In the first call of function foo a copy of pointer p (x) is actually created within the function and deleted as soon as the function ends, right? In the second call of foo the address of variable value is taken and a pointer x is created with that address and is deleted as soon as the function ends, right? Which of these calls is cheaper in terms of stack memory consumption? Or are both the same thing?
They're both similar. The first looks more expensive because you're creating a pointer twice, once as a local variable (inside main) and again as a function parameter (passed to foo), however the "optimization" phase of the compiler will probably turn the first into the second (assuming that the only thing you do with p is pass it, and you don't reuse it later in main).
They are almost identical. The only difference is that you have a pointer object p on the call stack in main, but if you're going to worry about that then you have issues. :)
In the first call, you are passing a variable containing the address of value.
In the second, you are passing the address of value directly.
Note that assignment operator says that both p and &value are the same, so you should be able to pass either one to the function as you have proven.
Pointers have values that can be copied like everything else. They
have value-semantics.
void foo(int* t);
takes a pointer by value. It will create a copy of the pointer
argument and use it inside its body.
int value = 23;
int *p = &value; // &value takes the address of value and use it to copy initialize p
foo(p); // copy the value of the pointer inside foo
foo(&value); // do the same but don't create a temporary