SIGSEGV segmentation fault in c++
A segmentation fault occurs when a program attempts to access a memory location that it is not allowed to access, or attempts to access a memory location in a way that is not allowed (for example, attempting to write to a read-only location, or to overwrite part of the operating system).Segmentation faults have various causes, and are a common problem in programs written in the C programming language, where they arise primarily due to errors in use of pointers for virtual memory addressing, particularly illegal access.
Let see example of segmentation fault error
I have a method btSize_iter(bnode*r) this return the size of binary tree.

While debugging I found signal SIGSEGV segmentation fault.
This means that I tried to access an invalid memory address.
This error comes at :
89 q.push(temp->left);
It means that temp->left may be accessing invalid location.
here temp is assigned by temp=q.front(); at
83 temp=q.front();
So now we will check how value is allocated to variables so we will debug and see the values of variables.
when debug started then first time values assigned to variables are:

now if we continue clicking next instruction then after some time it will show segmentation error as follow.
.
on checking values we found that temp value is unexpectedly different. So we came to know that q.front() has returned some value which is invalid. so to check what is initial value of q.front() when queue is create, to check we will define an extra variable temp1 and temp1 is assigned as q.front as follows.

here we can check the value of temp1.
here we can see temp1 is assigned to some unwanted value this process tell us that even there is no element in the queue then also q.front() return some unwanted value. This unwanted value may be some memory location.
If we continue , it will show segmentation fault error.
At the time of segmentation fault error we can see the value of temp and temp1 are same.
so this time temp has accessed some memory location where user are not allowed so this error is thrown by operating system.
So we will modify our code as follows:
In this modification, our method will return when we found that temp is equal to temp1(temp==temp1).
Now no segmentation fault will occur.
I hope this post might have helped you.
Thank You!




No comments :
Post a Comment