Discussion Locked

About Memory Alocation

0 helpful
7 replies
Closed to new repliesThis discussion is closed. It stays readable, but it takes no new replies.

Hi Friends this is question for 'C" Family,
Can two auto veriable one is single variable of type int and another is an array of int,uses same location(NOTE: I am not using UNION)? And that too I tested on two m/cs of different RAM(one is 62MB and another is 128MB)but still I am getting the same problem.
And what is possibality of same variable uses same address in memory when i run program different time???

7 replies

by ktirf

The answer to the first question is: BY NO MEANS. Two variables cannot be at one address at the same time (unless you use unions)! But, of course, they can if they are defined in different blocks of code.
As for my experience, the answer for the second question is: yes, it is quite possible. I've seen many cases when a variable was located at the same address in different runs.
Cheers!

by a.c

Not if they are both in the same scope, or if one is global and one local. Only if they are both locals in different functions could they have the same address (as variables are assigned and destroyed, memory locations are assigned and freed, so they could at different times occupy the same address)

Second part, very likely. If you boot up and run the same things in the same order they should always be assigned memory in the same order, so unless you start a couple of extra apps first, they will do just that (or if you have a nice memory leak somewhere they won't!!)

by marsh lion

1. Yes it can but you need to use a dangling pointer with a bit of luck. For example:
int *p;
if(1) // just to make a block
{
int a = 1;
p = &a;
} // a now distroyed - p is a dangling
// pointer
int a[10];

as a could well have been in an empty block of 10 when it was destroyed (at the end of the block) p could be pointing to somewhere in that array. Please note that even though a has been destroyed p can still be written too and changed as you would a normal pointer.

2. As seen in other replies to this question there is definity a chance which is low (unless you have defined some address at compilie time (VERY DANGERIOUS)

This discussion is closed to new replies.