Last Updated On By Khizer Ali
When you are working on a project, and your code runs not as expected and you get a simple message of segmentation fault in php. Isn’t it the worst scenario for any PHP developer?
Well, in this article, we are going to discuss what is segmentation, why segmentation fault occurs, and how to identify the line of code which cause the issue for PHP.
Table of Contents
Segmentation is a term generally used in the operating system as a technique of memory management. In other words, it is the process of dividing the computer’s memory into segments or sections. It is the fundamental element of an operating system to control the memory. All procedures or task which has to perform in a computer are stored in the different segments of memory.
A segmentation fault occurs because of the Memory Access Violation. Means, the error occurs when a program tries to access a block of memory which you are not allowed to access. Or to make it concise, you are approaching memory location which doesn’t belong to you.
In short, it is also known as a segfault. There are various reasons for this error.
For example, take an example of the following program.
<?php
function printNum(){
return printNum();
}
printNum();
?>
This is the case of infinite recursion. In recursion, there is a maximum amount of depth you can recurse, which is based on the size of your stack.
Technically it is infinite so, it will throw an error.
What you need to do is add a base case in this recursion to stop it from consuming the whole stack.
<?php
function printNum($i){
if($i == 10)
return;
echo $i . " ";
return printNum(++$i);
}
printNum(0);
?>
This code will print the numbers from 0 – 9.
When a segfault happens, and you don’t know where, and it is challenging to find because you have hundreds or thousands of lines in your code. So I recommend you to use Xdebug. It is an extension of PHP which assist you with the debugging and development.
Segmentation fault can occur in any programming language if you try to access the restricted part of the memory. In this article, I have cleared things about segmentation, reasons for why the segmentation fault occurs and how to cope with it. I hope it is helpful for you.