Home > OS >  Does C let a program compiled by itself to return pointer to an array to be used directly?
Does C let a program compiled by itself to return pointer to an array to be used directly?

Time:05-12

For example, if I have some code string like this:

std::string code = R"( 
   #include<thread>
   #include<iostream>
   int main() 
   { 
       int array[@@size@@]; 
       std::cout<<&array[0]<<std::endl;
       std::this_thread::sleep(1000000000);
       return 0; 
   } 
)";

then if I save it to a file programmatically and compile it like this:

system("g   code.cpp"); 

then run it and parse its output, can I directly use the address to access the array in any way without getting segfault? Does a process have any way of sharing simple arrays to enable faster messaging or other purposes without using any other APIs?

I mean, does it have an advantage on having more freedom on accessing it if the program is compiled & run by current process, with C ?

CodePudding user response:

As far as C is concerned there may not even be a concept of processes. They are mentioned in the standard as far as I can tell only twice.

Once in a recommendation about lock-free atomics suggesting that they should also work when shared between processes and once with regards to possible causes of file system races.

Anything about actually sharing memory between processes would be operating system dependent and will therefore likely require some operating system specific API calls.

CodePudding user response:

Converting an integer literal to a pointer is implementation defined and might be completely meaningless. The only integer literal you can safely convert into a pointer is 0 and that turns into nullptr.

So even ignoring all the stuff about processes being in different address spaces and protected from each other on modern OSes you still couldn't access that array in a portable way.

And you certainly couldn't access the array one the other process has finished.

  • Related