0

For some reason I can't understand, when I am initializing the aim variable within the main function, I get a error bus error ./a.out. However, if I initialize the aim variable outside the main function, it compiles with no error. I was able to complete the challenge but I am just curious why this is. I would greatly appreciate an explanation.

Here is my working code:

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

int aim = 0;

int main(void)
{
    int horizontal = 0;
    int depth = 0;
    int result = 0;

    FILE *data;
    data = fopen("data.txt", "r");
    if (data == NULL)
    {
        printf("This file doesn't exist.\n");
        return 1;
    }

    char* direction;
    int num;
    while(!feof(data))
    {
        fscanf(data, "%s %d", direction, &num);

        // printf("%s ", direction);
        // printf("%d\n", num);

        // Take variables and do arithmetic
        if ((strcmp(direction, "forward")) == 0)
        {
           horizontal += num; 
           depth += (aim * num);
        }
        else if ((strcmp(direction, "up")) == 0)
        {
            // depth -= num; // PART 1
            aim -= num;
        }
        else if ((strcmp(direction, "down")) == 0)
        {
            // depth += num; // PART 1
            aim += num;
        }
    }

    result = horizontal * depth;

    printf("Answer: %i\n", result);

    fclose(data);
    return 0;
    
}

(If you move the aim declaration to inside the main function, you should get the error I was receiving).

  • 6
    Almost certainly not a direct result of the `aim` variable placement. The actual issue is that `char* direction;` is an unintialised pointer variable. Writing to it with `fscanf` results in Undefined Behaviour. UB means the behaviour is unpredictable and can change with seemingly unrelated code changes. It can crash, get wrong results, appear to "work" and any other behaviour. – kaylum Dec 29 '21 at 04:09
  • 4
    Also see: [Why is “while ( !feof (file) )” always wrong?](https://stackoverflow.com/questions/5431941/why-is-while-feof-file-always-wrong) – kaylum Dec 29 '21 at 04:09
  • 1
    Max Santos, Who or what text suggested `while(!feof(data))`? – chux - Reinstate Monica Dec 29 '21 at 04:10
  • Compilers can often warn you about uninitialized variables, if you ask them to. Use `-Wall`. – Nate Eldredge Dec 29 '21 at 05:32

0 Answers0