1

My task is to create a sorting algorithm for integer values read from a file. The values have to be sorted in an array, as the amount of values is variable, I've used a dynamic array of integers (actually my first time).

Now, the algorithm seems to work fine as it prints all values in the correct order, but only until there are 6 values to sort. In that case, there's no output whatsoever, it seems like even the sorting process isn't successful anymore.

Here's my code:

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

void swap(int *a, int *b){
..
}

int main(){
    int i,anzahl,sorted=0,bla;
    FILE *fp;
    int* feld;

    fp=fopen("file","r");
    if (fp==NULL) return 0;
    else {
        fscanf(fp,"%i",&anzahl);
        feld=(int*)calloc(anzahl,sizeof(int));
        for (i = 0; i <= anzahl; ++i) {
            fscanf(fp,"%i",&bla);
            *(feld+i)=bla;
        }
        fclose(fp);
        while (sorted==0){
            for (i = 0; i < anzahl-1; ++i) {
                if (feld[i]>feld[i+1]) swap(&feld[i],&feld[i+1]);
            }
            for (i = 0; i < anzahl-1; ++i) {
                if (feld[i]<=feld[i+1]) sorted=1;
                else {sorted=0; break;}
            }
        }
        for (i = 0; i <anzahl; ++i) {
            printf("%i ",feld[i]);
        }
    }
    return 0;
}

Please excuse the German variable names and the newbie-style code.

If now the content of my "file" is as follows:

6
1
5
1
99
7
8

the program won't work. If I change the number of values, everything is fine, but as long as the number of values is 6, the program won't work, no matter what values there are.

3
  • what is void swap(int *a, int *b) { .. } is the function too complex to post it? Commented Jan 29, 2015 at 15:56
  • You could just do some search+replace for the variable names. And perhaps rename bla permanently in your source Commented Jan 29, 2015 at 15:57
  • No, in fact I thought it'd be easy enough to understand it's function just by it's name. It simply swaps a and b. Commented Jan 29, 2015 at 15:58

1 Answer 1

2

You are going out of bounds causing undefined behavior here:

for (i = 0; i <= anzahl; ++i)
               ^

This line should be comparing less than not equal or less than.

Also checking calloc() return value is always a good idea.

Sign up to request clarification or add additional context in comments.

3 Comments

@asdfqwer No particular reason really. It is undefined behavior.
replace <= with <.
Well, okay, now I get it. That's embarrassing. Thank you very much everyone.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.