Interview Question
Country: United States
Shondik is correct. We would get different results on different machine and also on different compilers.
+1 for Griffindor!
@Luv can you tell why won't it print the garbage value if memory allocated to array is in stack?
@shondik : But its not printing garbage values . It is printing 1's . It will print garbage value only when if in function g() , size of array >12 . When size of array in g() > 12 , then it is printing 12 1's and rest as garbage values .
Explain this behavior .
@Barney, @luv, I want to share some of my concepts.
- Aashish July 02, 2012I request you to get your basic concepts clear & brushed up.
When you are calling f(), then memory is being allocated for array a[] on the stack, where you are initializing its sots with 1. Now, since this array has been allocated on the stack, the scope is local. When you return from the function, the memory gets freed up. However memory doesn't go anywhere. The OS maintains a free list of all the memory which has been freed & so, can be used by any other process. By garbage value, the process means that it is expecting any unusual value[it may mean 1 or value with figure like 84638290(Both are considered as garbage for that process)].
Now, coming to the point, When you call function g(), memory is being allocated for array b[], However, its just an accident that the same memory gets allocated that was being allocated to a[] & so, it contains all 1.
However, its never safe to rely upon such type of allocation[as its just an accident].
A different compiler, a different optimization settings would trap you.
Hope everything is clear.