Search code examples
cstrcmpnull-pointerargc

How to check for NULL pointer in C?


I have a homework in C for this semester, and the teacher said I should write this function not that complicated. I'm new to programming, and I can't seem to find the answer. He said we did some of this type of stuff in class, but I couldn't find anything like this.

int checkforerror(int argc){
    if (argc != 3) {
        fputs("Too little or too many arguments!\n", stderr);
        exit(EXIT_FAILURE);
    }
}

Also he pointed out, that I have to check for nullpointer in a function. I found some nullpointer check in some programs which we wrote in class, but I'm not sure it's good this way.

int mycmp(char *s1, char *s2){

    if (!(s1 && s2))
       return EXIT_FAILURE;

So we did something like this in lessons. Also I tought about this:

if (s1 == NULL && s2 == NULL)
   return EXIT_FAILURE;

I don't really know whether they are really null pointer checks and which should I use.

Can you please help me with these?


Solution

  • According to De_Morgan's_laws

    (not (A and B) = not A or not B)

    Your condition

    if (!(s1 && s2)) 
    

    is the same as

     if (!s1 || !s2))  //same as if (s1 == NULL || s2 == NULL)
    

    Here you are checking if any of s1 or s2 is NULL and if so you exit.


    But in second one

    if (s1 == NULL && s2 == NULL)
       return EXIT_FAILURE;
    

    if both s1 and s2 are NULL then you are exiting.

    If any of s1 or s2 are not NULL you will proceed further and will try to access them, thus invoking undefined behavior.