int main(){
int i = 0;
while(i < 2){
char str[10];
printf("%p\n", str); //outputs same address both the times
i++;
}
i = 0;
while(i<2){
char *str;
str = (char*)malloc(10*sizeof(char));
printf("%p\n", str); //outputs two different addresses
i++;
}
}
In the above code why declaring same character array in a loop gives the same address although variable is declared two different times. So as per my understanding it should allocate new memory to it. But it returns the same address every time.
In the second where memory is allocated dynamically to it, it returns two different addresses which is understandable as malloc will find new contiguous memory blocks for me everytime.
But why it prints the same address in the first case?
In your first example, char str[10];
is local variable valid only within scope of {
}
. After the scope ended, the variable is destroyed and the memory is "freed". The next alocation can be in the same space because it is empty and available.
In the second sample, you use malloc
... memory is not auto-released until you call free
(or program ends).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With