1

I have two C codes. test.c is

#include <stdlib.h>

int main ()
{
    int a;
    a = 5;
    return a;
}

test2.c is

#include <stdlib.h>

int main ()
{
    int a;
    a = 6;
    return a;
}

When I run them and I check the address in memory of the "a"s with gdb I get the same address. Why is this so?

Breakpoint 1, main () at test.c:7 7 return a; (gdb) print &a $1 = (int *) 0x7fffffffe1cc

Breakpoint 1, main () at test2.c:7 7 return a; (gdb) print &a $1 = (int *) 0x7fffffffe1cc

3
  • Why not? Both programs are equal (except the constant value). You're not checking the address of 5 and 6(no such thing), you're checking the address of a. Commented Mar 18, 2014 at 13:09
  • Did you mean: run them at the same time? Commented Mar 18, 2014 at 14:28
  • @david.pfx I run test.c first, then test2.c Commented Mar 18, 2014 at 18:31

3 Answers 3

5

The address of "a" is on the stack frame for your program. This is a virtual address, independent of where in physical memory your program is actually loaded. Therefore, it would not be surprising if both (almost identical) programs used the same address.

Sign up to request clarification or add additional context in comments.

Comments

4

Because each application in OS is run in its own memory space.

Address 0x7fffffffe1cc is not really physical address. This is made due to security - you cannot handle other process memory directly just like that. You also cannot handle devices directly.

You can read more about that here and here

Comments

1

It is very likely that your OS is using Virtual Memory for memory management. What this means is that addresses found within a given program are not 1:1 mapped to physical memory. This allows for a number of things (including running multiple programs that require lots of memory by page swapping to disk). Without virtual memory, if you were to allocate static int a rather than put it on the stack, the linker would do it's best to choose an address for it. If you then linked another program, it doesn't know what other programs may be using that address. Running two programs could stomp on the memory of the other program. With virtual memory, each program gets it's own slice of memory with it's own address 0x0 and it's own address 0x7fffffffe1cc.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.