Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Memory allocation and char arrays

Tags:

c++

c

I still do not quite understand, what exactly will happen in the situation:

int i = 0;
for(i; i <100; i ++)
{
    char some_array[24];
     //...
    strcpy(some_array,"abcdefg");

}

Will the some_array act as:

some_array = malloc(24);

At the beginning of the cycle and free(some_array) at the end of the cycle?

Or those variables are gonna be allocated in the stack, and after the function ends destroyed?

like image 802
Vanya Avatar asked Jan 09 '23 01:01

Vanya


2 Answers

some_array is local to the block, so it's created at the beginning of each iteration of the loop, and destroyed again at the end of each iteration of the loop.

In the case of a simple array, "create" and "destroy" don't mean much. If (in C++) you replace it with (for example) an object that prints something out when it's created and destroyed, you'll see those side effects happen though.

like image 190
Jerry Coffin Avatar answered Jan 16 '23 16:01

Jerry Coffin


There are two ways of storing character strings. 1. Creating some space using malloc and then storing the char string In this case memory is allocated from heap and will not be freed until you free it explicitly. Here memory is not deallocated even after the scope 2. Creating an array and storing in it Here memory is allocated from stack and is freed implicitly after the scope

like image 22
Saisujithreddy Avatar answered Jan 16 '23 16:01

Saisujithreddy