Why does my C program print "(null)" during execution of tolower conversion of characters?

StackOverflow https://stackoverflow.com/questions/16932482

  •  31-05-2022
  •  | 
  •  

Question

I wrote this program to try to understand C a little better. It works, but for some reason, (null) is printed before the correct output. My code:

/* This program will take a string input input from the keyboard, convert the
string into all lowercase characters, then print the result.*/

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

int main()
{
    int i = 0;
    /* A nice long string */
    char str[1024];                               
    char c;
    printf("Please enter a string you wish to convert to all lowercase: ");

    /* notice stdin being passed in for keyboard input*/
    fgets(str, 1024, stdin);  //beware: fgets will add a '\n' character if there is room       

    printf("\nYour entered string: \n\n%s\n", str);
    printf("\nString converted to lowercase: \n\n%s\n");
    while(str[i]) { //iterate str and print converted char to screen
        c = str[i];
        putchar(tolower(c));
        i++;
    }
    putchar('\n'); //empty line to look clean
    return 0;
}

Incidentally, I noticed that when if my string variable is added to the last printf function, the problem goes away.

Replace:

printf("\nString converted to lowercase: \n\n%s\n"); 

with

printf("\nString converted to lowercase: \n\n%s\n, str");

Here is a sample output showing the issue:

Please enter a string you wish to convert to all lowercase: THE QUICK BROWN FOX
JUMPED OVER THE LAZY DOG.

Your entered string:

THE QUICK BROWN FOX JUMPED OVER THE LAZY DOG.


String converted to lowercase:

(null)
the quick brown fox jumped over the lazy dog.

Press any key to continue . . .
Was it helpful?

Solution

This print statement:

printf("\nString converted to lowercase: \n\n%s\n");

Has a %s in the format string, but you didn't pass an argument to match with it.

You're getting lucky that a 0 happens to be passed, and that your printf implementation gracefully handles that by printing (null). You're in undefined behaviour territory here.

If you turn on some more warning flags, your compiler will likely warn you about this kind of problem. In a quick test here, Clang didn't even need any flags:

$ clang example.c -o example
example.c:20:51: warning: more '%' conversions than data arguments [-Wformat]
    printf("\nString converted to lowercase: \n\n%s\n");
                                                 ~^
1 warning generated.

and neither did GCC:

$ gcc example.c -o example
example.c: In function ‘main’:
example.c:20: warning: too few arguments for format
example.c:20: warning: too few arguments for format
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top