I can't understand why my program is facing a segmentation fault.

I decided to make my own program which counts the number of steps used in Collatz Conjecture(as discussed in week 4). The picture below is of the function which counts the steps using recursion.The main function is not included in the picture since I didn't use any pointer in the main function.

I tried declaring " int i " and "int* c" globally rather than locally in function collatz_steps() and still I came across the segmentation fault.

[I do realize that code discussed(in "shorts") by Mr.Lloyd is much better. I just wanted to write a program of my own and found this problem which I couldn't understand]

enter image description here


You have segmentation fault because you recur forever and eventually i gets big enough to exceed 4 bytes that you assign to *c so you touch memory that does not belong to you => segmentation fault.

It does not stop because n never equals to 0. Collatz Conjecture promises that n == 1 sooner or later, not 0.

Also, there are other minor things about your code:

  • after n == 1 and return, main forgets about int *c. value is still there but you can not access it. So, if you want to keep this value for the future, declare int *c in main. Or, if you do not need, you may just print it before exit:

      if (n == 1)
         return 0;
  • return i that you put in the end will never work. you should either put it before exit instead of return 0, or just delete it.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .