Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is the following C code safe?

Tags:

c

#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

like image 316
ghayalcoder Avatar asked Mar 30 '10 13:03

ghayalcoder


2 Answers

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.

like image 68
DevSolar Avatar answered Oct 03 '22 20:10

DevSolar


Do you mean something like this?

  char* result = foo ();
  printf ("result is %s\n", (result ? result : "NULL"));
like image 43
Paul Beckingham Avatar answered Oct 03 '22 21:10

Paul Beckingham