Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Declaring a character array VS dynamically allocating space to character array in C

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?

like image 345
Rahul Arora Avatar asked Dec 23 '22 20:12

Rahul Arora


1 Answers

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).

like image 88
Martin Perry Avatar answered Jan 01 '23 15:01

Martin Perry