Reputation: 171
The following program gives different results when compiled using gcc compiler, and 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?
Upvotes: 0
Views: 160
Reputation: 653
As clearly explained by others, c + 2[p] - 6[p] - 1 is past the array bounds.
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. 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'. 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.
Upvotes: 0
Reputation: 41017
strlen(c+2[p]-6[p]-1)
is translated to strlen(((c + 't') - '2') - 1)
= strlen(((c + 116) - 50) - 1)
, thus, accessing outside of the bounds of the string (undefined behaviour).
Upvotes: 4