I’ve read several answers for this question but can’t fully understand. How does the compiler know the end of an array. If we suppose that an array of 4 int is located in memory just before an another int, can we by mistake write array[4] and it will give us this 5th int? I suppose no so how the compilers knows there are only 4 elements?
>Solution :
If you’re lucky, the compiler might spot that you’re writing beyond the end of the array, and flag it as a warning, but it’s not actually a compile-time error.
If you have this code:
static int a[4];
static int b;
// ...
a[4] = 42;
You’d actually discover that b now has the value 42, unless the compiler decided to put it somewhere else.
Yes, it’s that easy to overrun an array in C. There are no guard rails.
In fact, this behaviour is explicitly relied upon in some places. You might declare a struct as follows:
struct comms_block {
enum comms_block_type block_type;
size_t len;
uint8_t variable_data[1];
};
And then, when you wanted to create a comms block of type t, with variable data length l, you would use a function like this:
struct comms_block *new_comms_block(enum_comms_block_type t, size_t l) {
struct comms_block *b =
(struct comms_block *)malloc(sizeof(struct comms_block) - 1);
b->block_type = t;
b->len = l;
return b;
}
The function returns a struct comms_block with len bytes of space from variable_data[0] onwards.
You can safely index variable_data[] using any value up to (len - 1) despite that it’s only declared as a single-byte array in the struct definition.