csegmentation-fault

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.


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.