C++, how to access with a pointer to a specific address - c++

I was curious, so I tried to do this:
First program:
#include <iostream>
using namespace std;
int a = 5;
int main()
{
cout << "Value of a: " << a << endl;
cout << "Address of a: " << &a << endl;
system("pause");
return 0;
}
Output:
Value of a: 5
Address of a: 0x472010
Second program:
#include <iostream>
using namespace std;
int* p = reinterpret_cast<int*>(0x472010);
int main()
{
cout << "Value of p: " << *p << endl;
cout << "The address that the pointer points to: " << p << endl;
cout << endl;
system("pause");
return 0;
}
So, I want to read the value of the variable 'a' with
the 'p' pointer belonging to the another program, and the 'p' pointer point to specific address.
everything is fine until i run the second pragram, as the second program doesn't give the desired results
Output second program:
Value of p: 4661264
The address that the pointer points to: 0x472010
The result does not change if I keep the window of the first program open.
I promise I’m a beginner and I’m trying new things
What am I doing wrong?

You can't directly access another process's memory in the manner you are attempting. Each process runs in its own address space. Your 2nd process is trying to access an (invalid) address within its own address space, not within the address space of the 1st process.
On Windows, to read another process's memory, your 2nd process must obtain a HANDLE to the 1st process, such as from OpenProcess(), and then must use ReadProcessMemory() to read memory from an address within the 1st process.
The alternative is for the 1st process to allocate a block of shared memory which the 2nd process can access directly. On Windows, you can use CreateFileMapping() and MapViewOfFile() for that purpose (see Creating Named Shared Memory on MSDN). On 'Nix systems, you can use shm_open() mmap().

Related

Pointers pointing to same memory location but different program

I've written two programs, one (p1.cpp) that prints the value and address of a variable every 1 second..
// p1.cpp
int main() {
int x = 13;
int *p = &x;
while (true) {
cout << " value of x: " << *p << " addr: " << p << endl;
sleep(1);
}
}
and the other (p2.cpp), in which I manually point a pointer to the location printed out by p1.cpp and change the value.
//p2.cpp
int main() {
int *p = (int*)0x61ff08; // this is manually set and compiled.
cout << "value of p from p2.cpp : " << *p << endl;
*p = 10;
}
However, upon running p1.cpp, setting the location and running p2.cpp, the value in first program doesn't seem to change. In fact, p2.cpp shows some garbage value if I display the contents of p.
output of p1.cpp
output of p2.cpp
I would like to know why is this happening and why the value of x isn't changed by the pointer of another program.
Thanks!
In modern operating systems like linux, windows or MacOs each process has its own virtual memory address space.
Therefore the memory address from the process of your program p1 has nothing to do with the memory of the process of your program p2.
If you really want to access memory between processes directly you need to use shared memory.
But what is your intention? Do you just want to play around, or do you want communication between processes? In the later case you should read about IPC - inter process communication. There are a lot of IPC mechanisms you can use like named pipes, sockets or shared memory, depending on what you want to achieve.
You may have a look at this article for first introduction into the topic: https://en.wikipedia.org/wiki/Inter-process_communication

Is this a double free in C++

I thought the following code snippets would cause double free, and the program would core dump. But the truth is that there is no error when I run the code?
Similar problem shows that it caused double free!
My Question is why does there have no error show that there is a double free? And why does there have no core dump?
#include <iostream>
using namespace std;
int main()
{
int *p = new int(5);
cout << "The value that p points to: " << (*p) << endl;
cout << "The address that p points to: " << &(*p) << endl;
delete p;
cout << "The value that p points to: " << (*p) << endl;
cout << "The address that p points to: " << &(*p) << endl;
delete p;
cout << "The value that p points to: " << (*p) << endl;
cout << "The address that p points to: " << &(*p) << endl;
delete p;
}
The program's output when I ran this program is shown as followed:
After modifying the code snippet like the following, the core dump occured:
#include <iostream>
using namespace std;
int main()
{
int *p = new int(5);
for (;;)
{
cout << "The value that p points to: " << (*p) << endl;
cout << "The address that p points to: " << &(*p) << endl;
delete p;
}
return 0;
}
And the program output is :
So there is another question that why this program will core dump every time?
Yes, it is a double free (well, triple, really) which puts it into undefined behaviour territory.
But that's the insidious thing about undefined behaviour, it's not required to crash or complain, it's not required to do anything at all(a). It may even work.
I can envisage an implementation that stores the free state of a block in the control information for it so that freeing it twice would have no effect. However, that would be inefficient, and also wouldn't cover the case where it had been reallocated for another purpose (it would prevent double frees, but not a piece of code freeing the block when some other piece still thinks it still has it).
So, given it's not required to work, you would be well advised to steer clear of it since it may also download maniacal_laughter.ogg and play it while erasing your primary drive.
As an aside, modern C++ has smart pointers that are able to manage their own lifetime, and you would be doing yourself a big favour if you started using those instead of raw pointers.And, although the removal of raw pointer from C++ was a joke, there are some that think it's not such a bad idea :-)
(a) The C++20 standard has this to say when describing undefined behaviour in [defns.undefined] (my emphasis):
Behavior for which this document imposes **NO** requirements.
why does there have no error show that there is a double free? And why does there have no core dump?
delete p;
cout << "The value that p points to: " << (*p) << endl;
The moment you referenced to a deleted pointer is when the program entered an undefined behaviour, and then there is no guarantee that there would be an error or a crash.
It's not entirely the same, but the analogy between memory and a hotel room is applicable, which explains well what an undefined behaviour means. Highly recommended reading:
Can a local variable's memory be accessed outside its scope?

Would there be any possible issues with declaring a pointer value in separate lines in C++, instead of using the 'new' function?

I'm new to C++ and currently having a hard time with pointers.
I was wondering if there is a preferred method of coding between the two methods shown below:
#include <iostream>
using namespace std;
int main(){
// method 1
int* n;
*n = 2;
cout << "address of n in main(): " << n << "\n"; //returns 0
cout << "value inside of n in main(): " << *n << "\n"; // returns 2
// method 2
int* m = new int(2);
cout << "address of m in main(): " << m << "\n"; //returns some address
cout << "value insdie of m in main(): " << *m << "\n"; // returns 2
}
The first method returns the following:
address of n in main(): 0
value inside of n in main(): 2
The Second method returns the following:
address of m in main(): 0x6c2cc0
value inside of m in main(): 2
Q1. What would be possible issues with having the address of n in main():0? (it only behaves like this on an online compiler sorry. Nevermind this question.)
Q2. What is the "new" declaration method called?
What would be possible issues with having the "address of n in main():0"?
If you are lucky, crashing the program due to segfault. If you are not, memory corruption, undefined behavior, etc.
The reason is that you are using an effectively random memory address that has not been mapped/reserved/allocated to your process.
What is the "new" declaration method called?
There is no "name" for the "method". new is a keyword and an operator, too. It is the standard way of allocating memory in C++. Although, in almost all cases, you will use a container instead that manages the memory for you, like std::vector or std::unique_ptr.

storing an object name during construction of another object

I wanted to create objects from the class “takeSnapshots” that would learn, upon their instantiation, the name of another object from the class “lock” that they could query later as the state of the “lock” object changes. I can think of multiple ways of letting the object from class “takeSnapshots” know which object it is to query (like including the name of the “lock” object as part of the call to its member functions). But, I thought it better to take care of the relation in the beginning and not worry later if I am calling the correct object combinations.
The included code shows stripped down versions of the two classes and example instantiations created in main.
I have included the outputs on each line following their respective couts.
What I expected was that the constructor of “takeSnapshots” would store away the address of the “lock” object. Then I could use it later when taking a snapshot. You can see that what gets stored away (at least when I use it to get numWheels) is a few addresses off from the address that the “lock” object thinks it has for numWheels.
I am mostly interested in knowing why this code does not work the way I expect, i.e, if this is not a good architectural idea, that is one thing. But with the behavior I’m seeing here, I’m clearly not ready to use pointers in anything complicated and I don’t want to give up on the basic architecture just because of erroneous implementation. Any help would be greatly appreciated.
// simpleTest.cpp : Demonstrates problem I'm having understanding
// pointer to an object.
#include "stdafx.h"
#include<iostream>
using namespace std;
class lock {
public: //Just while I run a test.
int numWheels;
lock(int numW) {
numWheels = numW;
cout << " \n In \"lock\" constuctor, address and value of numWheels
" << &numWheels << " " << numWheels << endl;
} //Values from console: 0034F874 and 4
};
class takeSnapshots {
lock* localLock;
public:
takeSnapshots(lock myLock) {
localLock = &myLock;
cout << " \n In \"takeSnapshots\" constuctor, address and value of
numWheels " << &localLock->numWheels << " "
<< localLock->numWheels << endl;
//Values from console: 0034F794 and 4 "Same value, but not the same
//address as expected from "lock."
}
void takeASnapSnapshot() {
cout << " \n When taking a snapshot, address and value of numWheels
" << &localLock->numWheels << " " << localLock->numWheels <<
endl;
//Values from console: 0034F794 and 2303449 "No longer even the
// same value as expected from "lock."
}
};
int main()
{
lock yourLock(4);
takeSnapshots myShots1(yourLock);
cout << " \n In main (from \"yourLock\"), address and value of
numWheels " << &yourLock.numWheels << " " << yourLock.numWheels <<
endl;
//Values from console: 0034F874 and 4 "Still the same values as set
//in the constructor of "lock."
//Take a picture
myShots1.takeASnapSnapshot();
return 0;
}

Allocating Dynamic Memory to PlayerID

For hours now I've been trying to work out to how I can assign dynamic memory to a certain playerid, when they join a server, and destroy it when they leave.
I've tried numerous things, I've tried making an array of pointers... which would allow me to access the information with the player ID using the pointer and array position:
int *pInfo[MAX_PLAYERS]; // Global
//Function Local
CPlayers p;
pInfo[playerid] = p;
Which doesn't work, it tells me it cannot convert the class initialisation to a memory pointer.
I tried the same thing, with this line instead:
std::unique_ptr<CPlayers> pInfo[playerid];
However it needs a constant expression where playerid is, this means I cannot do this unless I know what the player ID is and enter it directly... which is impossible as I won't know until they client tries to connect.
Does anyone have a solution that will allow me to make memory dynamically, and have this memory accessible via the playerid. Or some other fashion, that me indefinitely use that clients information in game.
As I have ran out of ideas... I can't find anything online. I'm new as well so there may be functions I've over looked.
Thanks.
You can use MAP container to do that. The ideia is that you have 2 values. The first one is the playerID and the second one, a dynamic memory reference, which contains its properties. Following is a simple example to prove the concept.
#include <map>
#include <memory>
#include <iostream>
int main()
{
std::map<int, std::unique_ptr<int>> pinfo;
// Inserting some elements.
pinfo.emplace(1, std::unique_ptr<int>(new int{3}));
pinfo.emplace(800, std::unique_ptr<int>(new int{700}));
for (auto& i: pinfo)
std::cout << "Player " << i.first << ", value " << *i.second.get() << std::endl;
// Deleting. Note that, due unique_ptr, the memory is deallocated automatically
pinfo.erase(1);
std::cout << "Player 1: deleted" << std::endl;
for (auto& i: pinfo)
std::cout << "Player " << i.first << ", value " << *i.second.get() << std::endl;
}