Just a miscellaneous question. I have a program in C++:
#include <stdio.h>
int main()
{
while (1) {
int value1 = 1;
printf("%p\n", (void *)&value1);
void* address = (void *)&value1;
int value2 = *(int*)address;
printf("%d\n",value2);
}
return 0;
}
What this does is get the address of value1, store it in address, and then get the variable in address and store it in value2. This works just fine, however, I would like to access the variable from another C++ program. I have tried this (two methods in this one file):
#include<iostream>
#include <cstdint>
int main() {
std::cout << "before seg fault" << std::flush;
uintptr_t p = <address>;
int value = *reinterpret_cast<int *>(p);
int value2 = *(int*)<address>;
std::cout << "after seg fault"<< std::flush;
std::cout << value;
return 0;
}
This causes a segmentation fault when trying to access the value, which is probably because the OS doesn't want me accessing this value or because it doesn't exist in this instance.
However unpractical and stupid this may seem, is there a way to overcome this? Or is it impossible? As a side note, Why should / why shouldn't I do this?
Edit: I have approved Chris's answer, as it works just fine when you run it with root on linux. Would it be too much to ask for something that works on Mac and Windows too? I have tried running the poke program on Mac system and it gives error: Can't access pid 26112:: No such file or directory, invoked by line:
fprintf(stderr, "usage: %s pid address value\n", av[0]);