Search code examples
cmacosexc-bad-accesslldb

EXC_BAD_ACCESS assigning to variable right after function call


I'm writing a very simple C program for a basic course, and I have been getting EXC_BAD_ACCESS on line 14. I can't see what the problem is. The program asks the user for a number, and then displays the ASCII character associated with it.

This only happens, AFAIK, when debugging my program with lldb. It works perfectly fine when running from the command line, or on onlinegdb.com. Also, if I comment out line 13, and assign true or false to loop_ctrl, instead of the return value of UserWantsToExit, everything works as expected.


    #include <stdio.h>
    #include <stdbool.h>

    void GetAndDisplayInput(void);
    bool UserWantsToExit(void);

    int main()
    {
        bool loop_ctrl = true;

        while (loop_ctrl)
        {
            GetAndDisplayInput();
            loop_ctrl = !UserWantsToExit(); /* EXC_BAD_ACCESS */
        }

        return 0;
    }

    void GetAndDisplayInput()
    {
        char input_char = '0';

        printf("\nInput a number: ");
        scanf("%i", &input_char);
        getc(stdin); /* Gets rid of '\n' */

        printf("\n\nIt's character '%c'!\n\n", input_char);
    }

    bool UserWantsToExit()
    {
        char choice = '0';
        bool value = false;

        printf("\nDo you want to exit? (Y/N): ");
        scanf("%c", &choice);
        getc(stdin); /* Gets rid of '\n' */
        value = (choice == 'y' || choice == 'Y');

        return value;
    }


Solution

  • The format descriptor %i used in the call to scanf() in function GetAdnDisplayInput() requires a corresponding argument of type pointer to int. You are passing a pointer to char. Undefined behavior is undefined.

    Note that your C compiler should have warned you about the mismatch between the format descriptor and the corresponding argument; you should make a habit of compiling with all possible warnings turned on.