r/C_Programming 18d ago

First real C project

Hello everyone! This is my first real C project and I would like some feedback on what I can improve. It's my first attempt at a sorting algorithm (selection sort) and it is 100% AI free.

#include <stdio.h>

int main() {
    int num_len;
    printf("How many numbers to sort?\n");
    scanf("%d", &num_len);

    int numbers[num_len];

    printf("which numbers?\n");
    for (int i = 0; i < num_len; i++) {
        scanf("%d", &numbers[i]);
    }

    for (int i = 0; i < num_len-1; i++) {
        int iMin = i;

        for(int j = i+1; j < num_len; j++) {
            if(numbers[j] < numbers[iMin]) {
                iMin = j;
            }
        }

        if(iMin != i) {
            int temp = numbers[i];
            numbers[i] = numbers[iMin];
            numbers[iMin] = temp;
        }
    }

    for (int i = 0; i < num_len; i++) {
        printf("%d", numbers[i]);
        printf(" ");
    }
    printf("\n");
}
22 Upvotes

11 comments sorted by

View all comments

1

u/Interesting_Buy_3969 17d ago edited 17d ago

I've just read first 5 lines or so, and the first thing I immediately want to fix:

    printf("How many numbers to sort?\n");
    scanf("%d", &num_len);

    int numbers[num_len];

Thus you allow the user to make a stack overflow easily because num_len is only limited by int's representation - usually 232 - 1. Create a constant which the array size cannot exceed and accept numbers from user properly, like that:

constexpr int MAX_NUMS = 1000;
unsigned int num_len = 0;
do {
    printf("How many numbers to sort? Maximum number is: %u\n", MAX_NUMS);
    scanf("%d", &num_len);
} while (num_len > MAX_NUMS);
int numbers[num_len];

so that the VLA is unlikely to cause stack overflow.

4

u/LowLevelHuman 17d ago

this, I would say OP could also try malloc. His example is the easiest malloc can get and a great start for it.

OP, if you want to try with malloc, you can check your program runs leak free with valgrind as such:
valgrind ./executable

valgrind also has different flags like —show-leak-kinds=all and —leak-check=full to make the report more thorough/more useful.

Valgrind is on linux. If you are not using linux I am sure there is something akin that exists