# segmentation fault dunnu why



## Kenshin (Feb 4, 2008)

I wrote a program for booth's  algorithm for signed multiplication.Attached is the c code...I am gettin segmentation fault...whyy 


kenshin@cutie:~$ ./a.out

Enter the two numbers
 -3
7

Segmentation fault (core dumped)
kenshin@cutie:~$


----------



## QwertyManiac (Feb 4, 2008)

*imgs.xkcd.com/comics/compiler_complaint.png

Anyway, where's the attachment?


----------



## Kenshin (Feb 4, 2008)

Heres the attachment....actually we elex ppl are not much familier with C...pls check up wat pointers i hv messed up




```
#include <stdio.h>

#include <math.h>

 void bin(int l,int *mat);

 void add(int *tem1,int *tem2);

 void shift(int *k,int *l,int *j);

void print(int *tem5,int *tem6, int b);
/*A[4]={0,0,0,0},Q[4],M[4]={0,0,0,0},c[4]={0,0,0,1},C1[8]={0,0,0,0,0,0,0,1};*/

int main()

{

   int s,a,i,p,q,q1,m;

   int ans[8],A[4]={0,0,0,0},Q[4],Q1=0,M[4]={0,0,0,0},c[4]={0,0,0,1},tee[4],C1[8]={0,0,0,0,0,0,0,1},x,z,d;

   printf("\nEnter the two numbers\n ");

   scanf("%d%d",&q,&m);

   printf("\n");

   printf("Binary equivalent of 1st no is ");

   bin(q,Q);

   printf("\n");

   printf("Binary equivalent of 2nd no is ");

   bin(m,M);

   printf("\n\nOpr      A    Q    Q(-1)");

   printf("\n\nInit --- ") ;

   print(A,Q,Q1);



   i=0;

   while(i<4)

   {

    if((Q[3]==0)&&(Q1==1))

    {

    add(A,M);

    printf("\nA+M ---- ");

    print(A,Q,Q1);

    }

    if((Q[3]==1)&&(Q1==0))

    {

     for(p=0;p<4;p++)

     {tee[p]=M[p];

     tee[p]=1-tee[p];

     }

     add(tee,c);

     add(A,tee);

     printf("\nA-M ---- ");

     print(A,Q,Q1);

    }

    shift(A,Q,&Q1);

    i++;

    printf("\nShift -- ");

    print(A,Q,Q1);

   }





for(i=0;i< 4;i++)

ans[i]=A[i];

for(i=0;i< 4;i++)

ans[i+4]=Q[i];

if(((q< 0)&&(m>0))||((q>0)&&(m< 0)))

{

for(i=0;i< 8;i++)

ans[i]=1-ans[i];

for(i=7;i>=0;i--)

{

x = ans[i];

ans[i]=d^x^C1[i];

if(((d==1)&&(x==1))||((x==1)&&(C1[i]==1))||((C1[i]==1)&&(d==1)))

d=1;

else

d=0;

}

}

printf("\n\n");

for(i=0;i< 8;i++)

printf("%d",ans[i]);

s=0;z=0;

for(i=7;i>=0;i--)

{

s = s + (pow(2,z) * ans[i]);

z = z+1;

}

if(((q< 0)&&(m>0))||((q>0)&&(m< 0)))

printf("\nTHE ANSWER IN DECIMAL IS : -%d\n",s);

else

printf("\nTHE ANSWER IN DECIMAL IS : %d\n",s);



return 0;

}





void add(int *tem1,int *tem2)

{



 int c=0,i,p;

 for (i=3;i>=0;i--)

 {

 p= tem1[i];

 tem1[i]=p^c^tem2[i];

 if((p&&c) || (p&&tem2[i]) || (tem2[i]&&c))

 c=1;

 else c=0;

 }

}





void bin(int l,int *mat)

{

int i,c[4]={0,0,0,1};

mat[i]=0;

if(l>0)

{

for(i=3;i>=0;i--)

{

   mat[i]=l%2;

   l = l/2;

}

}

else{

l= -1*l;

for(i=3;i>=0;i--)

{

   mat[i]=l%2;

   l= l/2;

   mat[i]= 1-mat[i];

}

add(mat,c);

}

for(i=0;i<4;i++)

printf("%d",mat[i]);

}



void shift(int *tem3,int *tem4,int *j)

{

 *j=tem4[3];

 tem4[3]=tem4[2];

 tem4[2]=tem4[1];

 tem4[1]=tem4[0];

 tem4[0]=tem3[3];

 tem3[3]=tem3[2];

 tem3[2]=tem3[1];

 tem3[1]=tem3[0];

}



void print(int *tem5,int *tem6, int b)

{

 int i;

for(i=0;i<4;i++)

printf("%d",tem5[i]);

printf(" ");

for(i=0;i<4;i++)

printf("%d",tem6[i]);

printf(" ");

printf("%d",b);

}
```


for sum unknown reason..was not able to attach file


The program works perfectly fine in turbo C...not in linux tho...and in college we hv fedora machines.


----------



## mehulved (Feb 5, 2008)

You need to attach math library in gcc.

```
gcc filename.c -lm
```


----------



## Kenshin (Feb 5, 2008)

no...i mean i complied with the -lm thing...the prob is when i run the file..THe program asks for the 2 numbers.after enterin the numbers the segmentation fault occurs


----------



## Faun (Feb 6, 2008)

Kenshin said:


> no...i mean i complied with the -lm thing...the prob is when i run the file..THe program asks for the 2 numbers.after enterin the numbers the segmentation fault occurs


compile with -g flag and then
debug it to get the correct location.

My net is down so cant do much, hope u can debug.
Steps
1) compile with $ gcc -Wall -g -o outputfile inputfile.c
2) start gdb session $ gdb outputfile core

More here *www.unknownroad.com/rtfm/gdbtut/gdbsegfault.html


----------



## nileshgr (Feb 6, 2008)

Kenshin said:


> I wrote a program for booth's  algorithm for signed multiplication.Attached is the c code...I am gettin segmentation fault...whyy
> 
> 
> kenshin@cutie:~$ ./a.out
> ...





			
				wikipedia said:
			
		

> A *segmentation fault* (often shortened to *segfault*) is a particular error condition that can occur during the operation of computer software. 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). Systems based on processors like the Motorola 68000 tend to refer to these events as _address_ or _bus_ errors.
> Segmentation is one approach to memory management and protection in the operating system. It has been superseded by paging for most purposes, but much of the terminology of segmentation is still used, "segmentation fault" being an example. Some operating systems still have segmentation at some logical level although paging is used as the main memory management policy.
> On Unix-like operating systems, a process that accesses invalid memory receives the SIGSEGV signal. On Microsoft Windows, a process that accesses invalid memory receives the STATUS_ACCESS_VIOLATION exception.
> 
> ...



SRC: *en.wikipedia.org/wiki/Segmentation_fault


----------



## fun2sh (Feb 14, 2008)

half of our class wil fail (wen results comes for 3rd sem) in the DATA Strucructer lab BECOZ OF THIS SEGMENTATION FAULT. 

dont know wat the hell i the problem with linux. 

me too had once got this error durin error n after seein i became extremely nervous n scared but i did some modification n that prog whic was ABSOLUTELY CORRECT PROG (WHICH WAS EXACTLY SAME AS THE ONE I HAD DONE  ON MY LAPPY IN TC N GOT OUTPUT) TO GET RID OF the frightening SEGEMNTATION FAULT. n we use such a stupid compile n linux. it really wierd to point out the errors. for seg fault it even doesnt tell where has it occured. **** LINUX N ITS STUPID COMPILER WE R USIN. we use vi edit n "cc" to compile the prog. teachers r damn stupid n dont know why dont they move to a better alternative like Visual c++


----------



## Kenshin (Feb 14, 2008)

Yeah ...my program works fine in windows...dunnu whhy not in linux


----------



## eggman (Feb 14, 2008)

This segmentation faults had driven me mad!!!!!!!!!!!!!!The the worst thing is that it won't even point where's the problem. Just Segmentation Fault.Nothing else.

Even when you just type the ditto prog,thats in the book..this occurs, because of a simple mistake, which could've been pinpointed.


----------



## mehulved (Feb 15, 2008)

I took some help of a friend, this is what we did
1) Copied the code to a file named prog.c
2) Compiled it like this

```
gcc -Wall -o prog prog.c -lm -ggdb
```
3) Then we ran it through the debugger

```
gdb ./prog.c
(gdb) run
Starting program: /usr/home/mehul/prog

Enter the two numbers
 1
2


Program received signal SIGSEGV, Segmentation fault.
0x08048b6d in bin (l=1, mat=0xbfbfe740) at prog.c:208
208     mat[i]=0;
(gdb) run
The program being debugged has been started already.
Start it from the beginning? (y or n) y
Starting program: /usr/home/mehul/prog

Enter the two numbers
 1 3


Program received signal SIGSEGV, Segmentation fault.
0x08048b6d in bin (l=1, mat=0xbfbfe740) at prog.c:208
208     mat[i]=0;
(gdb) bt
#0  0x08048b6d in bin (l=1, mat=0xbfbfe740) at prog.c:208
#1  0x08048687 in main () at prog.c:30
```

So, the problem is at line 208.
Here's what he had to say about it


> he is trying to subscript a pointer..big no..afaik



BTW, where do you get the value of i on line 208?
As, I can see you've just declared i but you haven't defined it.
I tried by changing i to 100 and program worked fine.
I dunno how it worked in Turbo C.


----------



## Krazy_About_Technology (Feb 15, 2008)

you are using the subscript i without initializing it.

you have written

```
int i,c[4]={0,0,0,1};

mat[i]=0;
```

here i is defined and then used as subscript in the array without initialization. This is causing problem. 
GCC is a very good compiler and as a student you should use it instead of more 'forgiving' compilers which let you make mistakes that cause problems in long run. I have myself seen borland compiler missing many memory leak scenarios which are reported in advance in GCC. If you want to learn C or C++ by Standards, GCC is one of the best compilers to have.


----------



## mehulved (Feb 15, 2008)

And BTW, FYI, you have 2 unused variables 

```
prog.c:18: warning: unused variable `a'
prog.c:18: warning: unused variable `q1'
```


----------



## mehulved (Mar 2, 2008)

It worked for me
Just add this line before line no. 208

```
for(i=3;i>=0;i++)
```

You're right your teachers are really stupid to make you use gcc, you should rather stick to cosy old tc++, it makes programming so easy. gcc is just a piece of crap.


----------



## FilledVoid (Mar 2, 2008)

Sarcasm as its best ^ . Most people think gcc sucks and are happy with TC. Just wait till your job uses anything BUT TC.


----------



## praka123 (Mar 2, 2008)

^no, blame Linux also as "he" does @#8 !that will be even more sweeter as Linux contains gcc  all fault of gcc and Linux.

yeah using vim/vi editor is a very big sin  sheesh..where these fellas are going?


----------



## QwertyManiac (Mar 2, 2008)

What was the need to drag Linux into this topic? Its a compiler-specific and helpful output, not Linux, nor Windows and not any other "Platform".

If you don't know to code with pointers, please avoid doing so. Applies to you eggman. Its even better if you fail, for not understanding what you code. Atleast after that it'd kick some sense into you about 'proper programming'.

So you say that you have never encountered a segmentation fault in Windows? Thats cause the programs compiled on your stupid old compiler don't tell you what's wrong, they just cease to function and crash midway. Good ol' BSOD eh? Prefer that, really, its worth your doom.

If you wish to change your ways, use GNU Debugger along with GCC. It wasn't invented for nothing. Nothing is.

Over that, I don't know what good would using a non-conformal compiler like VC++ 03/05 do to an eventually bad code of yours. Have you ever tried assembly? It makes you think better, try that first.


----------



## vish786 (Mar 2, 2008)

QwertyManiac said:


> If you don't know to code with pointers, please avoid doing so. Applies to you eggman. Its even better if you fail, for not understanding what you code. Atleast after that it'd kick some sense into you about 'proper programming'.



@others, well thats reason most dont tend to use pointers !


----------



## mehulved (Mar 2, 2008)

QwertyManiac said:


> If you don't know to code with pointers, please avoid doing so. Applies to you eggman. Its even better if you fail, for not understanding what you code. Atleast after that it'd kick some sense into you about 'proper programming'.


Not everyone is a good programmer like you


----------



## Krazy_About_Technology (Mar 2, 2008)

@mehulved : Well not everyone is a good programmer, but why is he studying programming then, to always be a 'not good programmer", huh? 

In my opinion, old TC is not good enough even for beginners due to its forgiving nature. It causes you to 'learn' doing mistakes that cause havoc in big, real world programs. If gcc is a crap, then Linux and whole of its software repository is crap, which it is not , that even a noob can tell.

Pointer arithmetic is an important topic in C and C++ and no great programs can be made without learning it properly. Uninitialized variables before use, null pointers etc are so big of a problem that all the new programming languages are coming with strong checking for these troublesome chunks of code. are they all crap???


----------



## Kenshin (Mar 3, 2008)

gcc is great no doubt bout tat...i just wanted to find the mistake tho..



fun2sh said:


> half of our class wil fail (wen results comes for 3rd sem) in the DATA Strucructer lab BECOZ OF THIS SEGMENTATION FAULT.
> 
> dont know wat the hell i the problem with linux.
> 
> me too had once got this error durin error n after seein i became extremely nervous n scared but i did some modification n that prog whic was ABSOLUTELY CORRECT PROG (WHICH WAS EXACTLY SAME AS THE ONE I HAD DONE  ON MY LAPPY IN TC N GOT OUTPUT) TO GET RID OF the frightening SEGEMNTATION FAULT. n we use such a stupid compile n linux. it really wierd to point out the errors. for seg fault it even doesnt tell where has it occured. ***** LINUX N ITS STUPID COMPILER WE R USIN. *we use vi edit n "cc" to compile the prog. teachers r damn stupid n dont know why dont they move to a better alternative like Visual c++



sorry to say but ur wrong tho....only thing i like bout my college is tat its entirely linux


----------



## gary4gar (Mar 3, 2008)

^^^^
huh! using linux in college
Do you live in INDIA?


----------



## Faun (Mar 3, 2008)

programming is not all about executing a program.

Its the ability of a developer to divulge every minute possible error and warnings(yup warnings count too) and get it endorsed 99% bug free.


----------



## praka123 (Mar 3, 2008)

gary4gar said:


> ^^^^
> huh! using linux in college
> Do you live in INDIA?


ya.most of the colleges(engineering esp) in my state uses linux I think.esp fedora or Debian.


----------



## Kenshin (Mar 3, 2008)

yeah i am from Fr agnels Bandra Mumbai....We have all Solaris,Red hats and fedoras


----------



## The_Devil_Himself (Mar 3, 2008)

my college too uses linux though teachers are usually clueless about it but the system admistrators are pretty intelligent.

+! for using GNU debugger,I used it only a few times and it was able to pin-point the problem exactly in the first go.


----------



## praka123 (Mar 3, 2008)

I have tried submitting stack trace or backtrace (whatever u call it!) of applications that crash in Debian Sid using gdb ,strace etc to BTS via reportbug tool 

not to say that I am clueless about the o/p it is showing.Indeed it is very helpful if u do bug reports of apps in Linux.  (bug-buddy in Gnome automates!)

Here is a howto:
HowToGetABacktrace - Debian Wiki 
StackTraces - Fedora Project Wiki


----------



## axxo (Mar 4, 2008)

gary4gar said:


> ^^^^
> huh! using linux in college
> Do you live in INDIA?



for ur info..our college has got a dedicated solaris lab with servers & thinclients...
I have come across this error...most of the time it will be due to improper assignations and illegal referencing...like if you miss out '&' in scanf will lead to this error..and gcc reports this message for most of the error..so quite difficult to trace..havent said that its not a problem with gcc..somewhere the program has got some error need to be corrected.


----------

