Search code examples
clinuxalgorithmubuntuselection-sort

I don't get all the values of my (int) array from Selection Sort algorithm


I'm programming on Ubuntu 14.04 using the gcc compiler.

I am using the rand(); function to give values to the elements of my array.

( rand() % 101; actually, so I don't get values higher than 100 )

Then I want to sort the elements of my array using the 'Selection sort' algorithm, but when I print(f) them out, the first two elements are 0's, even though there are no 0's on my array (most of the time).

Here's my code, please review it, compile it, try it out and guide me:

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

int main() {
    int i, j, tam_arreglo;
    time_t t;
    int *a;
    int aux;
    /* Here I'm asking for you to give me the size of the array and store it in tam_arreglo */   
    printf("Introduzca el tamaño del arreglo: \n");
    scanf("%d",&tam_arreglo);

    /* Making my array the size I just asked you */
    int array[tam_arreglo];
    srand((unsigned) time(&t));
    /* Dynamic random filling of the array */
    printf("El arreglo sin ordenar es: \n");
    a = malloc(tam_arreglo * sizeof(int));
    for(i = 0 ; i < tam_arreglo ; i++) {
        a[i] = rand()%101;
        printf("%d\n", a[i]);
    }
    free(a);
    /* My 'Selection sort' algorithm */
    for(i = 0; i < tam_arreglo; i++) {
        for(j = i+1; j < tam_arreglo; j++) {
            if(a[i] > a[j]) {
                aux = a[i];
                a[i] = a[j];
                a[j] = aux;
            }
        }
    }
    /* Here's when I get the error, the first two elements printed are 0's */
    printf("El arreglo ordenado es: \n");
    for(i = 0; i < tam_arreglo; i++) {
        printf("%d\n", a[i]);
    }

    return(0);
}

What am I doing wrong?


Solution

  • You should not free() the array yet, when you will no longer access the memory pointed to buy the pointer, then you call free() but never before.

    When you access the a pointer in the code following free(a); there will be garbage because the memory was free()'d already.

    So, move free(a) after the second for loop just before return and it should work well.

    And also, you don't need to use parentheses with return, and check the value returned by scanf() in case of invalid input, since in that case tam_arreglo will be uninitialized and your program will invoke undefined behavior.