Compiling C file is fine, but exe file displays nothing

88 views Asked by At

I've been trying to figure out what's going on, but it's driving me nuts. I have this script here, it compiles fine (I'm using GCC), but when I try to run the compiled exe, the terminal just pauses for a brief moment and exits. I have no clue what's going on, any help would be appreciated.

// not sure what's on
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include "extra.h"
int RanNum(int StartNum, int StopNum);
int main() {
    printf("Hey\n");
    int magicNum, guess, choice;
    do {
        printf("Guess the right number: ");
        scanf("%d", &choice);
        guess = 1;
        magicNum = RanNum(3,10);
        if (choice == magicNum){
            printf("You win! \n");
            break;
        } else {
            int rem = (3 - guess);
            printf("\nYou have %d tries remaining \n", rem);
        }
        guess++;
    } while (guess <= 3);
    if (guess > 3) {        
        printf("You lost... We can try again...\n");
    }
    return 0;
}

int RanNum(int StartNum, int StopNum){  
    int *list;
    int Divided;
    int range = StartNum - StopNum;
    int RandArray[range];
    for (int i=StartNum; i<StopNum; i++) {
        for (int j=0; j<range+1; j++) {
            RandArray[j] = i;
        }
    }
    list = RandArray;
    Divided = (StartNum+StopNum)/range;
    return list[Divided];   
}
1

There are 1 answers

0
dxiv On BEST ANSWER
  • RanNum runs into UB (undefined behavior) and a silent exit is one possible manifestation of UB.

    int RanNum(int StartNum, int StopNum){  // <---- called with StartNum = 3, StopNum = 10
        int *list;
        int Divided;
        int range = StartNum - StopNum;     // <---- range = 3 - 10 = -7
        int RandArray[range];               // <---- array of negative size       *** UB
        for (int i=StartNum; i<StopNum; i++) {
            for (int j=0; j<range+1; j++) { // <---- after 'range' is fixed to be > 0
                RandArray[j] = i;           // <---- the last iteration j = range
            }                               // <---- overruns the array bound     *** UB
        }
    // ...
    }
    
  • Once the first problems are fixed, there is another one with the main loop.

    int magicNum, guess, choice;  // <---- 'guess' is defined but not initialized
    do {
        printf("Guess the right number: ");
        scanf("%d", &choice);
        guess = 1;                // <---- 'guess' is initialized to '1` in each iteration
    
        /* code that does not change or use 'guess' */
    
        guess++;                  // <---- 'guess' was '1' and is now incremented to '2'
    } while (guess <= 3);         // <---- always true, so loop continues until number guessed