3
#include <stdio.h>
#include <string.h>


int main()
{
   char *ret = NULL;

   printf("ret: %s\n", ret);
   printf("%s\n", ret);

   return(0);
}


ret: (null)
Segmentation fault

The outputs are different, the result should be "segmentation fault", since ret points to nothing!

Why it outputs "(null)" when I just add "ret:" in printf()?

4
  • Because you have made it point to NULL Commented Aug 22, 2017 at 14:57
  • 2
    If the format string is exactly "%s\n", gcc optimizes the whole thing to puts(). See linked duplicate for details. Commented Aug 22, 2017 at 14:58
  • 1
    "the result should be "segmentation fault"," --> No, it is undefined what happens in this case. Commented Aug 22, 2017 at 15:05
  • 1
    Yes, you're right! Thanks @chux Commented Aug 22, 2017 at 15:38

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.