Search code examples
pointersdynamicheap-memorymemory-address

Failure accessing a variable through its adress from another application


I am working on a Qt application on my raspberry pi 4 and I want to create a dynamic variable and to use it in my Qt application , it is a counter and I don't want it to be reinitialized at zero on every execution of the application, I want to just use the address and increment the value on each execution.

so in my raspberry pi I created a variable

#include<stdio.h>


int main (void)
{
        int *p;
        p = (int*)malloc(sizeof(int)); 
        *p=10;

        printf("%p",p);
        //free(p);
return 0;
}

I compiled it and this is the output, so the adress of the variable created is 0xfa9150

pi@raspberrypi:~ $ gcc -Wall  impulsions.c -o impulsions
pi@raspberrypi:~ $ ./impulsions 
0xfa9150

in my Qt application I tried to read the value of the address but couldn't

int* counter=new int;
    counter=0xfa9150;

    qDebug()<<"counter"<< *counter;
    delete counter;

and I had this error

error: invalid conversion from ‘int’ to ‘int*’ [-fpermissive]
     counter=0xfa9150;
              ^~~~~~~~

can someone please explain to me how to do this


Solution

  • The memory spaces of different processes on your system (e.g. the Qt application and your program with the counter) are mostly disjoint. Even when they use the same addresses - those are virtual, not physical, memory addresses, and get translated upon use, (typically) into addresses in physical memory.

    That means that the Qt application does not, and cannot, have access to a counter variable in another process' memory space.

    So... you will need another approach. Some possibilities:

    • The Qt application communicates with your monitor mini-app over some some socket.
    • No second process, but the Qt application locks a file, opens that file, reads the current counter from it, adds 1, writes it back, closes and unlocks.
    • Use some existing utility/system facility which keeps track of execution statistics (I don't know of one personally, but it might exist, depending on which OS you're running).