0

I have a problem with this simple array assignment. When I use lower numbers such as 100, 1000, etc. the program works well. But if I use a larger number like 1000000 the program crashes at the following line :

int list[listLength];

and I don't know why.

The following example works well:

int main(int argc, char* argv[]){
   const long long listLength = 1000;
   int list[listLength];

   return 0;
}

But the following example does not work:

int main(int argc, char* argv[]){
    const long long listLength = 1000000;
    int list[listLength];


    return 0;
}

using de gdb debugger, i get the following error message just in the assignment:

error line:

int list[listLength];

error message:

Signal received: SIGSEGV (Segmentation fault) For program algorithms, pid 5.252

iam building it on 64 bits pc (for 32 bits target) with mingw32 using c++11.

Why doesn't the second example work?

Fabian Orue
  • 193
  • 2
  • 14
  • 1
    You are stepping out of bounds. `list[i+left]`. What happens when `i == listLength - 1`? – AndyG Apr 06 '17 at 16:56
  • Recursion can eat up the stack quickly. There are many examples on the interwebs of non-recursive bubble sort. – 001 Apr 06 '17 at 16:59
  • I've nominated this for re-opening because while it is an example of stack overflow (on Stackoverflow.com which is always nice). The real answer is to unwind the recursion and make this a `do`-`while` loop in about 3 lines of editing. – Persixty Apr 06 '17 at 17:05
  • @AndyG i fixed what you said to me, but the error persists. Thanks! – Fabian Orue Apr 06 '17 at 17:16
  • 1
    Bubble sort is one of the simplest (and one of the worst) sorting algorithms. Bubble sort is not recursive in any normal implementation. – crashmstr Apr 06 '17 at 17:51
  • OK, i changed the recursion for do while but the problem persists but a bit different, when i use 100000 as listLength all works well but if use 1000000 and debug the application get a segmentation fault in main function at line: int main(int argc, char* argv[]){ – Fabian Orue Apr 06 '17 at 18:04
  • i get the following error line 71: 6704 Segmentation fault (core dumped) sh "${SHFILE}" – Fabian Orue Apr 06 '17 at 18:17
  • 1
    100000 probably overflows the stack by the sheer size of the array (nearing 400MB). You will have allocate the array on the heap. However notice you'll require 10 billion iterations! – Persixty Apr 06 '17 at 21:57
  • 1
    As @DanAllen has mentioned, your array is too large for the stack. You need to allocate to the heap: `int *arr = new int[listLength];`. You must do `delete [] arr;` when you are finished with it or you will have a memory leak. – msitt Apr 06 '17 at 22:10
  • thanks very much guys! that solve the problem! – Fabian Orue Apr 06 '17 at 22:23

0 Answers0