-1

From what I understand, C arrays can't grow dynamically. But why does index=5 & 6 work below?

char carray[5];
carray[0] = 'a';
printf("carray[0]=%c\n", carray[0]);
carray[5] = 'b';
printf("carray[5]=%c\n", carray[5]);
carray[6] = 'c';
printf("carray[6]=%c\n", carray[6]);

Output:

char_array[0]=a
char_array[5]=b
char_array[6]=c

4thSpace
  • 43,672
  • 97
  • 296
  • 475

3 Answers3

5

There is nothing in C that prevents you from reading or writing beyond the bounds of an array. The memory after your array where elements 5 & 6 live might be another variable or a function or who knows what and by assigning that memory new values, you could cause your program to crash. Or it might just work. You have no way of knowing what the result will be, as you're causing undefined behaviour.

It's good practice to be fully aware of how big arrays or chunks of allocate memory are and to not go beyond them ever!

Chris Turner
  • 8,082
  • 1
  • 14
  • 18
1

you get that result because it is memory trash, it is not yours.

maybe this will help C Undefined Behavior

It is good to point that trying to access this could result in segmentation fault, or cause security issues (buffer overflow)

reinaldomoreira
  • 5,388
  • 3
  • 14
  • 29
1

As explained in other answers, just because you don't see any adverse effects does not mean they are not there. Here is an example to help see the kind of damage overrunning an array can cause. (I ran it online at https://www.codechef.com/ide)

#include <stdio.h>

int main(void) {
    char a1[4]={'A','B','C',0};
    char a2[4]={'E','F','G',0};
    char a3[4]={'I','J','K',0};
    a2[4]='Z';
    printf("%s %s %s\n", a1, a2, a3);
    return 0;
}

The output of this program is ABC EFG ZJK

The letter I of array a3 has been overwritten with a Z

Overrunning array a2 actually corrupted a3

Note: Depending on the environment, the overwrite could have hit elsewhere or crashed the program. For example running the same code at https://www.tutorialspoint.com/compile_c_online.php results in ZBC EFG IJK

GroovyDotCom
  • 1,304
  • 2
  • 15
  • 29