简体   繁体   English

C中字符串函数strlen()的不同输出

[英]Different output for the string function strlen() in C

The following program gives different results when compiled using gcc compiler, and turbo C 当使用gcc编译器和turbo C编译时,以下程序给出不同的结果

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

void main()
{
    char* c = "gatecs2017";
    char* p = c;
    printf( "%d", (int)strlen( c + 2[p] - 6[p] - 1 ) );
}

Somebody please explain the working of the program. 有人请解释该程序的工作原理。 Also why it generates different results? 还有为什么会产生不同的结果?

strlen(c+2[p]-6[p]-1)转换为strlen(((c + 't') - '2') - 1) = strlen(((c + 116) - 50) - 1) ,因此,访问字符串边界之外的内容(未定义的行为)。

As clearly explained by others, c + 2[p] - 6[p] - 1 is past the array bounds. 正如其他人清楚地解释的那样,c + 2 [p]-6 [p]-1超出了数组范围。

Where exactly, and why different results, here's the redundant explanation that hasn't been given yet: 确切的位置以及为什么会有不同的结果,这是尚未给出的多余解释:

c+116 is an address on your stack that's address of c + 116 bytes. c + 116是堆栈上的地址,即c + 116字节的地址。 Then call strlen(address) and you'll get the length of the area starting from c+116 on your stack until there's a '\\0'. 然后调用strlen(address),您将获得堆栈中从c + 116开始的区域长度,直到有一个'\\ 0'。 Since that area is uninitialized or is set differently by different compilers since it's likely somewhere in your executable when loaded to the memory by the kernel running your executable (assuming a kernel ran it), you'll get different results with each compiler-output executable. 由于该区域尚未初始化,或者由不同的编译器进行了不同的设置,因为当运行可执行程序的内核将其加载到内存中时(假设内核运行了该区域),它可能位于可执行文件中的某个位置,因此每个编译器输出可执行文件都会得到不同的结果。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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