Is the following C code safe?

Posted by lali on Stack Overflow See other posts from Stack Overflow or by lali
Published on 2010-03-30T13:31:55Z Indexed on 2010/03/30 13:33 UTC
Read the original article Hit count: 302

Filed under:
#include<cstdio>
#include<stdlib.h>

int main()
{
    char* ptr=NULL;
    printf("%s",ptr);
    return 0;
}

It prints (null) as output. The above is a sample code. In real code i get char* as a return of a function and i wish to print the character string for logging. However, NULL is also a valid return value of that function and so i am wondering if a null check is required before printing the character string?

char* ptr=someFuncion();
// do i need the following if statement?
if(ptr!=NULL)
{
  printf("%s",ptr);
}

I just want to be sure that the output would be same i.e if ptr=NULL then output should be (null) on all platforms and compilers and the above code(without if statement) would not crash on any C standard compatible platform.

In short, is the above code(without the if statement) standard compatible?

Thanks for your help and patience :)

Regards

lali

© Stack Overflow or respective owner

Related posts about c