I was trying to assign a value to a location outside of an array in a demo program in C. The array was of type int
, and I thought it might overflow into the next variable I had declared, b
. However, after running the program, my shell returned 1 and aborted. When I added the static
keyword to the array and the integer, the program printed the value of the variable, b
. However, I'm not sure why. What does the static keyword do in this context, and what difference does it make?
Take this piece of code:
#include <stdio.h>
int main(void)
{
int a[4];
int b;
a[4] = 42;
printf("%i\n", b);
}
When I run it, the program outputs 1\n zsh:abort ./memory
and exits.
However, when I modify it to be the following:
#include <stdio.h>
int main(void)
{
static int a[4];
static int b;
a[4] = 42;
printf("%i\n", b);
}
The program now outputs 42
. I have heard that the static keyword can have multiple uses in C, but what is it doing here that changes the program's behavior? I have looked at many definitions and still don't get it :(
Of course, what you're asking is explaining undefined behavior in C. As it suggests, what happens is up to the compiler that builds your code and the computer you're using.
But most compilers and most computers have it so the stack grow top down, not bottom up. Which means that the local variable b
has a memory address lower than the local variable a
.
The static keyword makes the variable stored into the global/static storage of the program, where apparently they've been stored with a
before b
, hence the static variable b
has a memory address higher than the static variable a
.
Overall, you should not assume anything from undefined behavior. It could do anything, and you're up for surprises.