0

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?

9
  • 1
    Could you also provide the outputs, please? Commented Feb 14, 2017 at 8:52
  • 0 in turbo C and 1 in gcc. Also I got 23 when run in codeBlocks Commented Feb 14, 2017 at 8:54
  • Turbo C hasn't been updated since 1988 - do you mean Turbo C++ instead? Commented Feb 14, 2017 at 8:54
  • 4
    Do you know what e.g. 2[p] does? Do you know anything about pointer arithmetic? What is the result of c + 2[p]? What is the result of c + 2[p] - 6[p]? What is the result of c + 2[p] - 6[p] - 1? Is that result a valid pointer to a valid and terminated string? Commented Feb 14, 2017 at 8:54
  • 3
    It's undefined behaviour. Commented Feb 14, 2017 at 8:55

2 Answers 2

4

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).

Sign up to request clarification or add additional context in comments.

2 Comments

Excuse me if I am asking a blunder. What is the meaning of c+116?
@elantra: its pointer arithmetic, an example :char *str = "maria" + 2; gives you "ria", this example is valid but yours is not (because you exceed the len of the string, as char *str = "maria" + 116;)
0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.