Is the following C code safe?
- by lali
#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