문제

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 ?

도움이 되었습니까?

해결책

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

다른 팁

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.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top