Search code examples
cstringnullpointerexceptionnullnull-pointer

Stuck with null pointer and empty string check


Im new to C and programming. I tried to make an uppercase program but I should do null pointer check and empty string check. How could I continue? i just want to understand this.

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

int *toUpper(char *str)
{
    int i;
    for (i = 0; i < strlen(str); i++) {
        if (str[i] >= 'a' && str[i] <= 'z') {
            str[i] = str[i] - 'a' + 'A';
        }
    }
    return str;
}

int main(int argc, char **argv)
{
     for (int i = 1; i < argc; ++i)
     {
         printf(toUpper(argv[i]));
     }

}

Solution

  • First of all, let me tell you, if you don't need format conversion (using conversion specifiers), use puts(), instead of printf().

    That said, you need to check two things for your toUpper() function:

    1. You need to check whether the incoming argument is a null pointer or not before accessing. You can check the incoming pointer against NULL, like

      int *toUpper(char *str){
          if (str) {             //makes sure `str` is not a NULL pointer
            // do operation
           }
            // else 
           return NULL;      //indicate error condition
       }
      
    2. You need to check if the supplied string is not empty. For that, you can check whether the first element is NUL or not, using:

      int *toUpper(char *str){
          if (str) {
             if (str[0] != '\0')     // check the first element
            // do operation
           }
            // else 
           return NULL;      //indicate error condition
       }