Reputation: 59089
I wrote the following code.
<?php
function f(){
return f();
}
f();
and get the output
$ php test.php
Segmentation fault
Why? I didn't use any pointers.
This is StackOverflow ?
Upvotes: 3
Views: 5704
Reputation: 67745
This comes specifically from the XDebug extension.
Running GDB, you will see:
Program received signal SIGSEGV, Segmentation fault.
0x00007ffff41f7e48 in xdebug_add_stack_frame (zdata=Cannot access memory at address 0x7fffff5fefa8
) at /build/buildd/xdebug-2.1.0/build-php5/xdebug_stack.c:772
772 /build/buildd/xdebug-2.1.0/build-php5/xdebug_stack.c: No such file or directory.
in /build/buildd/xdebug-2.1.0/build-php5/xdebug_stack.c
If XDebug is disabled, it will execute until the memory_limit
is reached. If your memory_limit
is too high, you might exhaust RAM and start swapping, freezing/crashing your machine.
Upvotes: 1
Reputation: 3933
This is a case of infinite recursion, but that is not specifically the cause. It is a stack overflow. When you have recursion, whether infinite or not, there is a max amount of depth you can recurse (add to the stack) which is based on the size of your stack (in bytes).
Technically this is infinite, but you won't get any errors for quite a while:
<?php
function f(){
sleep(1);
return f();
}
f();
What you need is known as a base case
in your recursion in order to stop it before it consumes the entire stack.
<?php
function f($i){
if($i == 10)
return;
echo $i;
return f(++$i);
}
f(0);
Which will print 0 to 9.
The segmentation fault
error is coming from the operating system, reporting the PHP application has encountered an issue adding to the stack. That won't make it to your script because at the system level the binary which makes up PHP has failed.
Upvotes: 7
Reputation: 1339
The infinite recursion you've set up continues to add stack frames until you overrun the amount of memory assigned to the PHP process call stack, at which point you get a segmentation fault.
Upvotes: 0