csegmentation-fault

Segmentation Fault in Method


Picture of Code with the location of the segmentation fault I am extremely new to C (only other experience is Java and Python), so please keep that in mind. I am trying to create this helper method that will print out an Octal, Hex, and Decimal representation of the same number, with an input of a short val, and char mode. I do not understand why I am receiving a segmentation fault on the first printf statement where mode is, as it seems to be fine in concept. Please send help!

void print_bases (short val, char mode){
    if (val == 0){
        printf("* Base Values:\t       Input Mode: %s *\n", mode);
        printf("*%-3s%-8s:\t%04X%19s*\n", " ", "Hex", 0x0000, " ");
        printf("*%-3s%-8s:\t%06o%17s*\n", " ", "Octal", 000000, " ");
        printf("*%-3s%-8s:\t%d%22s*\n", " ", "Decimal", 0, " ");
    }else{
        printf("* Base Values:\t       Input Mode: %s *\n", mode);
        printf("*%-3s%-8s:\t%04X%19s*\n", " ", "Hex", val, " ");
        printf("*%-3s%-8s:\t%06o%17s*\n", " ", "Octal", val, " ");
        printf("*%-3s%-8s:\t%d%22s*\n", " ", "Decimal", val, " ");
    }
}

I tried looking up this issue online but nothing is working and I do not know what's going wrong to try to fix it as I am learning based off of examples more than anything else.


Solution

  • Regarding the lines:

    void print_bases(short val, char mode) {
                                ^^^^
    

    and (there are a couple of these):

    printf("* Base Values:\t       Input Mode: %s *\n", mode);
                                               ^^
    

    The correct format specifier for type char is %c, not %s.

    By using %s, you're telling printf that you will provide a char * (pointer) type and it should expect a C-style string (a series of chars ending with \0).

    That won't end well when it tries to use the char variable to dereference memory to get the characters of the string.

    Many compilers will notify you if the arguments to printf do not match the format specifiers, since it's undefined behaviour to do so. If you're using something like gcc, I would ensure you always compile with the flags:

    -Wall -Wextra -Werror
    

    This will report all warnings, extra warnings(1), as well as treating all warnings as errors so you're less likely to get suspect executables.


    (1) I've always been bemused at how gcc defines the word "all" :-)