-1

I have stumbled upon strange behaviour in following C program.

#include <stdio.h>
void main(void) {
 int ta = 0;
 int te;
 int ca;
 char fna[1];
 char e[12];
 FILE *fa = fopen("list.txt", "r");
 ca = fgetc(fa);
 while(ca != 10) {
  fna[ta] = ca;
  te = ta + 1;
  ta = te;
  ca = fgetc(fa);
 }
 fclose(fa);
}

list.txt can contain any line, with a newline.

the fna char limit is ignored and program runs successfully even if line contains more than 1 characters.

If I delete the declaration of e[12], the expected error starts to occur. (Also if I lower the variable e limit, error starts to occur too. Even though e is not used at all.

What can cause this issue? It seems that variable fna lends e's character space.

1 Answers1

1

C does not check if you do not write or read outside the memory allocated for the object. The programmer has to ensure that.

0___________
  • 60,014
  • 4
  • 34
  • 74
  • so the limit in square brackets only prepares buffer space for [n] amount of bytes, but does not act as a boundary/limit of given char variable? – user12938074 Feb 21 '20 at 11:14
  • C does no bounds checking by default. Bounds checking may be available in some libraries and compilers as extra options. Compiling with debug symbols (`-g` compiler option) and stepping through the compiled executable with a debugger such as `gdb` will reveal what is happening with the memory. – hellork Feb 21 '20 at 11:16
  • Thanks, I thought segmentation fault in C is caused by reaching any limit given in the program, or exceeding any limits, going over border. It seems it just goes over the limits – user12938074 Feb 21 '20 at 11:21
  • @hellork For native arrays there are only very limited possibilities for that, since the pointer to it may be passed around wildly and the size information of the array is not present then any more – Ctx Feb 21 '20 at 11:30
  • @user12938074 A segmentation fault _may_ happen. C actually provides no guarantee at all what happens if you write past array bounds, or otherwise access memory you’re not allowed to access. That’s often a source of serious errors, and one of the main things people consider hard about the language (the language itself basically gives you no help at all with sticking to its rules). – Cubic Feb 21 '20 at 16:36