Question

I am using c string library's strlen function.I passed a NULL string to it and found mysterious result.I know I am not supposed to pass NULL string but I need an explanation for it.The code looks something like this

main()
{
  int k;
  char *s=NULL;
  strlen(s);
  // k = strlen(s);
}

On my gcc compiler ,It runs fine with the comment. but if you will remove the comment in the line k=strlen(s);

it produces segmentation fault. Any explanation ?

Was it helpful?

Solution

This is the assembler code without assignment to the int variable

movq    $0, -16(%rbp)
movl    $0, %eax
leave
ret

the compiler don't call _strlen because the value will not used

OTHER TIPS

The first 'strlen' call that is not assigning its return value is probably being optimized out by your compiler.

Passing a null pointer to strlen results in undefined behvaiour. Anything could happen. Including seg-faults. And including no seg-faults.

If you want to know the exact reason, then you will need to look at the assembler code that your compiler generates. But this will not tell you anything useful.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top