简体   繁体   中英

Is the following C code safe?

#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 ie 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"));

如果有疑问,你不应该依赖于实现细节并执行额外的(ptr != NULL) - 这也是很好的编码实践。

根据我的经验,通常你会在没有if语句的情况下处于清晰状态,尽管我倾向于避免做出你所说的习惯......这已经很长一段时间了,但IIRC是我曾经使用过的Sun编译器如果你将一个NULL char *传递给printf()会导致部分或全部崩溃,所以包含检查更简单,更安全......我打算在使用宏形式的注释中,但我发现自从我开始打字以来,我在30秒内被其他3人殴打过它:)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM