Can someone explain to me why this is possible?

Viewed 111
int main ()
{
   char *strA = "abc";
   int tam_strA = strlen(strA);
   
   char strB[tam_strA];
   strB[0] = 'a';
   strB[1] = 'b';
   strB[2] = 'c';
   strB[3] = 'd';
   strB[9] = 'z';
   
   printf("%c", strB[9]);
   
   return 0;
}

It prints 'z' normally. Why it doesn't return segmentation fault error? Since I'm trying to access an index that shouldn't exist because the size (amount of indexes) of strB is equal to tam_strA which is equal to 3.

Also, is there any difference/problem on doing char strB[strlen(strA)]; instead?

2 Answers

C language does not have a specification that stops you from accessing invalid memory, nor does it guarantee a segmentation fault. The only promise which is made is that, if you attempt to access invalid memory, that will cause undefined behavior.

Segmentation fault is one of the possible outcomes, NOT the ONLY one.

That said, the only problem with

 char strB[strlen(strA)];

is that, strB will not be long enough to hold the content in strA, because it will lack one byte to hold the null-terminator. Sure, byte-wise use will be fine, but if you want to copy the content (or any content of the same length as strA) and use strB as a string, you'll run past the allocated memory (in absence of the null terminator), invoking undefined behavior.

You only get Segmentation fault when accessing the memory that you do not own. You own your entire stack. strB[9] is a valid memory access in the eyes of the OS. The reason that you shouldn't do this is because the compiler doesn't know that you're using that memory, so it might decide to use that memory for other uses. It's also good for improving readability and minimising mistakes from the programmer. And, the standard defines the using of undeclared memory to be undefined behaviour, so you can't use it safely. Declaring a variable like int x;(or an array) tells the compiler that you will use the memory at x.

This is actually related to this question: Why does the first element outside of a defined array default to zero?. Read the much more detailed answers over there.

Related