#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
No. ISO/IEC 9899:1999 (the C standard document) makes no statement about what should happen if
ptris NULL, so the behaviour is undefined. The library you used merely was friendly enough to give you some helpful output (“(null)”) instead of crashing.Include the explicit check for NULL.