the_naive
the_naive

Reputation: 3064

Mistake with NULL comparison in C

Could you say me what mistake I'm doing here? When I set url = NULL then compare whether it has NULL whether by if(strlen(url)!=0) or by if(url!=NULL) the program crashes or breaks up. I know it's very a simple thing but I'm doing something wrong.

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

void main()
{
    char* url="/v1.0/fafffsdf"  ;
    url=NULL;
    printf("%s\n",url);
    if(url!=0)
    {
        printf("It ain't NULL\n");
    }
    else
    {
        printf("It's NULL\n");
    }
}

Upvotes: 2

Views: 264

Answers (1)

Pavan Manjunath
Pavan Manjunath

Reputation: 28525

The crash is in

printf("%s\n",url);

The pointer is pointing to NULL and you are trying to read from there, effectively dereferencing a NULL pointer which will generate a segmentation fault.

Pointing to an empty string like

char *url = "";

is OK and quite different from pointing to a NULL location like

char *url =NULL;

which is dangerous if dereferenced.

An empty string has a valid location in memory and can be dereferenced. Its just that it has nothing in it expect a \0.

Upvotes: 11

Related Questions