why i get segmentation fault, where is the bug?

D

demosthenesk

hi to all,
i am a newbie to C++ and i want some help if you could ...

i try to implement a recursive linera search algorithm for learning
purposes but i get segmentation fault.
here is the code.

the problem appears when ULLI searchKey gets big values like 999999.
for small values like 254 the program works.

--------------------------------------------------------
#include <iostream>
using namespace std;
typedef unsigned long long int ULLI;

//prototypes
ULLI RecursiveLinearSearch(const ULLI *, ULLI, ULLI, ULLI);

int main()
{
const ULLI arraySize = 999999999; // size of array a
ULLI * a;
a = new ULLI [arraySize];
ULLI searchKey = 999999; // value to locate in array a
int element;

for ( ULLI i = 0; i < arraySize; ++i )
a[ i ] = i; // create some data

element = RecursiveLinearSearch( a, searchKey, 0, arraySize - 1 );

// display results
if ( element != -1 )
cout << "Found value in element " << element << endl;
else
cout << "Value not found" << endl;

return 0;
}



/
*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
~ Search Algorithms ~
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
// perform a recursive linear search on the data
ULLI RecursiveLinearSearch(const ULLI * array, ULLI key, ULLI low,
ULLI high )
{
// search array for key
if ( array[ low ] == key )
return low;
else if ( low == high )
return -1;
else
return RecursiveLinearSearch( array, key, low + 1, high );
} // end function recursiveLinearSearch


--------------------------------------------------------
 
I

Ian Collins

hi to all,
i am a newbie to C++ and i want some help if you could ...

i try to implement a recursive linera search algorithm for learning
purposes but i get segmentation fault.
here is the code.

the problem appears when ULLI searchKey gets big values like 999999.
for small values like 254 the program works.

Odds are you are running out of stack (too many recursions) or running
out of heap (too many big arrays). Running under a debugger should show
you which one.

Use uint64_t from <stdint.h> instead.
 
O

Old Wolf

        const ULLI arraySize = 999999999; // size of array a
        ULLI * a;
        a = new ULLI [arraySize];

There might be not enough memory for this allocation,
it would be prudent to check it.

Maybe something like:
try
{
a = new ULLI[arraySize];
}
catch( std::exception &e )
{
std::cerr << "Unable to allocate 'a': " << e.what() << std::endl;
return 1;
}
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,755
Messages
2,569,536
Members
45,013
Latest member
KatriceSwa

Latest Threads

Top