'When I call the C system() function, is the location of the new program's main() stack frame similar to the original program's main() stack frame?
I'm wondering if when I call the C system()
function, the location of the new program's main()
stack frame is similar to the original program's main()
stack frame. Do anyone knows?
Below is "Program1" which calls system()
to launch "Program2":
int main() {
int i;
system("Program2");
}
Here is "Program2":
int main() {
int i;
}
I know that main()
in "Program1" gets put on the stack, which means that the variable i
will be on the stack. Let's say the address of this i
in memory is 0x80000000
.
Now, when system("Program2")
is called and launches "Program2", the main()
function of this program gets put on a stack too; however, in a different memory space (as far as I am aware), so the i
for "Program2" will be in memory too, but in a different memory space from the i
in "Program1".
Even though both i
's will be in different memory spaces, will the address of i
in "Program2" be similar or close to the address of i
in "Program1" (0x80000000
)?
For example, could it be something like 0x80000004
or close?
Solution 1:[1]
In modern operating systems, each process has its own address space, using virtual memory, so the address of i
in Program1 could be the same as the address of i
in Program2, without referring to the same area of RAM.
Furthermore, 64-bit OSes use address space randomisation, giving the stacks of various processes or running instances of the same executables different addresses.
Finally, the variables i
in both processes may actually have no address at all as they could live in registers or be optimized out at compile time.
Merely printing the address with printf("%p\n", (void *)&i)
will force the compiler to at least temporarily allocate some space on the stack for i
.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | chqrlie |