1

I seem to be having some trouble getting this mergesort to run. When I try to run it with g++ the terminal says "Segmentation fault (core dumped)," and I don't know what is causing this to happen (you might be able to tell that I'm still a beginner). Could anybody help out?

#include <iostream>
using namespace std;


void merge (int*, int, int, int);

void mergesort (int* A, int p, int r){

 if (p < r){

  int q = (p+r)/2;
  mergesort (A, p, q);
  mergesort (A, q+1, r);
  merge ( A, p , q, r);
  }
}

void merge (int* A, int p, int q, int r){


  int n = q-p+1;
  int m = r-q ;
   int L [n+1];
  int R [m+1];

  for (int i=1;i <n+1;i++)
       L[i] = A[p+i-1];

  for (int j=1; j< m+1; j++)
      R[j] = A[q+j];

L[n+1];
R[m+1];

 int i= 1;
 int j=1;

for (int k = p; k= r + 1; k++){
   if (L[i] <= R[j]){
      A[k] = L[i];
       i+=1;
   }
   else{
     j += 1;
    }
}
}


int main() {

int A [15] = {1, 5, 6, 7,3, 4,8,2,3,6};

mergesort (A, 0, 9);

for (int i=0; i <9; i++){
cout << A[i] << endl;
}

return 0;
}

Thanks a lot!

  • What do you expect the statement `L[n+1];` to do? – Beta Nov 06 '13 at 01:02
  • Seriously, a segmentation fault can be caused by countless of things: buffer overflows, dereferencing dangling pointers, double frees, writing to read-only memory and loads more. Did you try running a debugger, or at least identifying some lines where the issue might be? – SevenBits Nov 06 '13 at 01:02
  • use a debugger to find the source of error, for example gdb on linux – Anycorn Nov 06 '13 at 01:02
  • Or better still, use [`std::inplace_merge`](http://en.cppreference.com/w/cpp/algorithm/inplace_merge) and write your entire merge sort in roughly eight lines of code (including whitespace). – WhozCraig Nov 06 '13 at 01:04
  • 1
    can you maybe explain your logic a bit here? A mergesort is supposed to take two sorted arrays and merge them into one sorted array, the fact that you only have one array to start with should be abstracted away. You should start by building a function that does what I mentioned above and work backwards from there, probably the easiest way to do something that relies on recursion. – Red Alert Nov 06 '13 at 01:04
  • @WhoozCraig: I assume, though, he's trying to implement his own version, perhaps for an assignment. An answer like that does him no justice. – SevenBits Nov 06 '13 at 01:05
  • 1
    @SevenBits which is why it is in a comment, and not an answer. And since the OP made no claims of what was *not* on the table for usage, its even more applicable. If you've got a problem with that, I'm sorry. Many people don't even know such functionality exists in the standard library, and I've just as much sense to assume the OP is one of those as you have to assume their status of fledgling student. – WhozCraig Nov 06 '13 at 01:10
  • @WhozCraig No, no problems. However, the way your phrase was worded made it sound (at least to me) like he should can his current approach to what you're suggesting. He asked a question; we should answer it instead of telling him to go a whole different route. But a do agree, it is wise to educate people about functions and classes that they might not know exist. – SevenBits Nov 06 '13 at 01:18
  • @SevenBits: Not when "a whole different route" is the route any sensible person should take in the first place. – Lightness Races in Orbit Nov 06 '13 at 01:47

2 Answers2

2

There are three things in your implementation that either don't make sense or are outright wrong:

First these:

L[n+1];
R[m+1];

Neither of these statement have any effect at all, and I've no idea what you're trying to do.

Next, a significant bug:

for (int k = p; k= r + 1; k++){

The conditional clause of this for-loop is the assignment k = r + 1. Since r does not change anywhere within your loop, the only way that expression is false is if r == -1, which it never is. You've just created an infinite-loop on a counter k that will run forever up into the stratosphere, and in the process index, and write, to memory no longer valid in your process. This, as a result, is undefined behavior. I'm fairly sure you wanted this:

for (int k = p; k< (r + 1); k++){

though I can't comment on whether that is a valid limit since I've not dissected your algorithm further. I've not take the time to debug this any further. that I leave to you.

Edit. in your main mergsesort, this is not "wrong" but very susceptible to overflow

int q = (p+r)/2;

Consider this instead:

int q = p + (r-p)/2;

And not least this:

int L [n+1];
int R [m+1];

Uses a variable-length array extension not supported by the standard for C++. You may want to use std::vector<int> L(n+1) etc.. instead.

WhozCraig
  • 65,258
  • 11
  • 75
  • 141
0

In your case the segmentation fault is likely being caused when you are trying to read memory in that does not exist for a variable, for example say you have an array called foo of size 10 (so foo[10]) and you this statement foo[11] would cause a segmentation fault.

What you need to do is use debug statements to print out your index variables (i, j, n, m, p and q) and see if any of these are larger than your array sizes

EDIT: Another unrelated issue is that you should not use using namespace std, this line of code can cause scoping issues if you are not careful, just something to keep in mind :)

Matthew Pigram
  • 1,400
  • 3
  • 25
  • 65
  • 1
    I would advise him to use a debugger to step through the code line by line, rather than telling him to use print statements. Print statements are a very bad way to debug in large programs. Instead, perhaps using Valgrind is a good choice...? – SevenBits Nov 06 '13 at 01:06
  • 1
    its not a large program and he is a beginner, debugging can be a bit overwhelming when starting out compared to the simplicity of print statements – Matthew Pigram Nov 06 '13 at 01:08
  • I concur with @SevenBits . If you've a debugger at your disposal and *don't* use it to track down issues like this, you're doing yourself a disservice. In fact, this is *ideal* precisely because it is so small. It isn't overwhelming, and developing debugger techniques now will literally pay for itself from then on. Yes its like using a hammer to kill flies, but going down the road to a bigger project, not knowing how to swing that hammer, and coming up on a granite rock with only a flyswatter will be even more painful. – WhozCraig Nov 06 '13 at 01:14
  • If you cannot use a debugger, you cannot develop software. It's that simple. – Martin James Nov 06 '13 at 01:20
  • 1
    @MartinJames This is wrong, and narrow-minded. http://stackoverflow.com/questions/1544289/purposefully-debugging-without-using-a-debugger – WiSaGaN Nov 06 '13 at 01:39
  • @WiSaGaN - OK, we have a difference of opinion that we will have to live with. I can support my position easily - there are 2-3 SO questions a day about simple linked lists alone that could have been sorted easily with a debugger. Unfortunately, those posters cannot develop software, and so prat about for a day and then post their buggy code on SO for someone else to debug. – Martin James Nov 06 '13 at 01:49
  • Either that, or they do know how to debug, but it's too much like hard work and it's easier to take the piss out of the skilled an experienced devlopers on SO by trying to con them into doing someone else's work for them. I don't blame the newbs/beginners, I blame the incompetent profs and tutors who let students get past 'Hello world' without any introducing any concept of debugging. – Martin James Nov 06 '13 at 01:55
  • Oh - and the ability to use a debugger is only one part of overall system development and testing. You need the debugger AND effective and comprehensive logging to get as many bugs out as possible. If the only 'logging' available is print statements, then fine, put that in as well, (NOT 'instead of') :) – Martin James Nov 06 '13 at 01:59
  • I never said they should not use a debugger, just that it might be something that the poster is not comfortable with, whereas the poster is almost certainly is aware of print statements/logging. If they have the time to spare then they most certainly should learn to debug effectively. – Matthew Pigram Nov 06 '13 at 02:07