Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Segmentation fault in C BogoSort

I’ve started learning c and wanted to program bogosort with it. I coded the most parts, but as I started it, I’ve got a segmentation fault error, but don’t know why.

That’s my code:

#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <stdbool.h>

int tries = 0;

int bogo[7];
int length = sizeof(bogo) / sizeof(bogo[0]);

void setBogo();
void printBogo();
bool bogoFinished();
void sortNew();

int main() {
    setBogo();
    
    while (!bogoFinished()) 
        sortNew();
        
    printBogo();
    printf("Versuche benötigt: %d", tries);

    return 0;
}

void setBogo() {
    srand(time(NULL));
    
    for (int i = 0; i < length; i++)
        bogo[i] = rand() % 100;
}

void printBogo() {
    for (int i = 0; i < length; i++)
        printf("Pos.: %d, Value: %d\n", i, bogo[i]);
}

bool bogoFinished() {
    int letzte = 0;
    
    for (int i = 1; i < length; i++)
        if (bogo[i] < bogo[letzte])
            return false;
        else letzte = i;
        
    return true;
}

void sortNew() {
    srand(time(NULL));
    tries++;
    
    for (int i = 0; i < length; i++) {
        int value = bogo[i];
        int ran = rand();
        
        bogo[i] = bogo[ran];
        bogo[ran] = value;
    }
}

How the code works:
First I set all the position in the array with random integer. Then, it’s checked in a while loop whether the array is sorted or not. If so, the array will be sorted random again. The algorithm for initializing the array worked before, so I think it’s caused somewhere in the resorting part.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

The culprit is bogo[i] = bogo[ran]; (and the following line too), because rand() returns values in the range from 0 to RAND_MAX, which is an unspecified, but usually pretty large integer; definitely bigger than your array of length 7.
To stay in range, use rand() % length instead.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading