Recently I stumbled upon source code where programmer declared variables inside one infinite loop depending on if/else conditions. What I found odd is that the code ran and it didn't implied any memory leaks. First I thought that maybe it was architecture specific thing (the code was for ARM) but I ran some tests and I found out that binaries on IA32 compiled with GCC acted in same way.
My approach was like this: I've created two small program foo.c and bar.c
Foo.c:
#include <stdio.h>
int main(void)
{
int i;
for(i=0; i<10; i++) {
char buf[10];
buf[i] = 0;
printf("buf[%d] (@ %#x) == %d\n", i, &buf, buf[i]);
}
return(0);
}
Bar.c:
#include <stdio.h>
int main(void)
{
int i;
for(i=0; i<10; i++) {
char *ptr;
ptr = (char *) malloc(10);
ptr[i] = 0;
printf("buf[%d] (@ %#x) == %d\n", i, &ptr, ptr[i]);
}
return(0);
}
The reason behind making explicit distinction between declaring an array in Foo.c and allocating memory in Bar.c was that first I thought that maybe compiler auto-magically detects that it's the same variable and just ignoring the declaration after initial for iteration which of course shouldn't be the case in Bar.c because I explicitly allocate the memory.
What was really weird to me that in both examples the address of both an array and allocated memory stays the same after initial for iteration.
I do not completely understand that and I don't have my copy of K&R with me so I'll be thankful for an explanation. (Also if I made any mistake in my reasoning I'd be glad for pointing it out.)