#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
In short, is the above code(without the if statement) standard compatible?
No. ISO/IEC 9899:1999 (the C standard document) makes no statement about what should happen if ptr
is 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.
Do you mean something like this?
char* result = foo (); printf ("result is %s\n", (result ? result : "NULL"));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With