stack out of scope ?
Steven Schveighoffer
schveiguy at gmail.com
Sun May 16 17:07:18 UTC 2021
On 5/16/21 12:32 PM, Alain De Vos wrote:
>
> Why doesn't this program dups core ?
> Is s not recycled ?
> ```
> import std.stdio:writeln;
> void main(){
> //I point to the heap
> int[] p=[1,2,3];
> {
> int[3]s=[1,2,3];
> //I point to the stack
> p=s;
> }
> //Why do I still live ?
> writeln(p[0]);
> }
>
> ```
To answer your question, why does this not dump core, it's because you
didn't access memory that was invalid. Stack memory, like most computer
memory, is allocated in chunks to the program. The OS typically
allocates pages at a time per request for it. Which means, even though
the memory isn't technically in scope, it's not going to cause a
segmentation fault (this is a hardware fault saying you accessed an
address that doesn't exist in your process).
In order for a dangling pointer (which is what this is) to cause a seg
fault, you have to release that memory back to the OS, and make that
address invalid before accessing. D very rarely gives memory back to the OS.
The more common problem for dangling pointers is that you access a piece
of memory that has since been reallocated to something else, and screw
up that something (generally a pointer).
-Steve
More information about the Digitalmars-d-learn
mailing list