Originally Posted by
std10093
So, I took a simulation of the final exams, with the exams of the previous year. I did well, but I missed question k on pointer arithmetic subject. I thought that the behavior was undefined, but A is printed normally. :/ Why?
Part of undefined behaviour is that it sometimes looks like it works. In your case it happens that the byte in front of s has the value 0. Thus strlen() returns 0 and you get a valid index for s.
Look at this example:
Code:
#include <stdio.h>
#include <string.h>
int main(void)
{
char *a = "999";
char* s = "ABCD";
char *b = "111";
printf("a: %p - b: %p - s: %p\n", (void *)a, (void*)b, (void*)s);
printf("%c(%d) - %u\n", *(s - 1), *(s - 1), strlen(s - 1));
printf("k)UNDEFINED s[strlen(s - 1)] = %c\n", s[strlen(s - 1)]);
char a2[] = {'Y', 'Y', 'Y', 'Y', 'Y' };
char s2[] = "ABCD";
char b2[] = {'X', 'X', 'X', 'X', 'X' };
printf("a2: %p - b2: %p - s2: %p\n", (void *)a2, (void*)b2, (void*)s2);
printf("%c(%d) - %u\n", *(s2 - 1), *(s2 - 1), strlen(s2 - 1));
printf("k)UNDEFINED s2[strlen(s2 - 1)] = %c\n", s2[strlen(s2 - 1)]);
return 0;
}
which produces this output on my computer:
Code:
$ ./foo
a: 0x8048700 - b: 0x8048709 - s: 0x8048704
(0) - 0
k)UNDEFINED s[strlen(s - 1)] = A
a2: 0xbf8474ad - b2: 0xbf8474b7 - s2: 0xbf8474b2
Y(89) - 5
k)UNDEFINED s2[strlen(s2 - 1)] = X
In the first block, all three string literals are stored next to each other. Thus the byte just in front of "s" is the null character of the string "a".
In the second block I use char arrays in order to influence the byte in front of "s2". As you can see in the output, it's the last character of array "a2". strlen() starts at this character and continues until it reaches the null character of "s2". Hence the length is one character too much. You can also see by looking at the addresses, that "b2" is again behind "s2" and now you are accessing the first character of "b2" (a 'X').
Bye, Andreas