I am quite new in C and I have a question about understanding one memory allocation issue:
So lets say I allocate memory for an int array:
int* my_array = malloc(sizeof(int)*10);
Now I know that a memory block of the given size has been allocated at position '&my_array[0]' (or just my_array).
SO:
If I know call a method to fill my array, I KNOW I should give as a parameter the pointer to my array in order to fill it, so something like:
void fill_array(int* array) {//..do something}
fill_array(my_array);
But I was wondering, what would happen, if the method itself allocates another memory block and I then try to set those equal, so what I mean is:
int* get_filled_array() {
int* result_array = malloc(sizeof(int)*10);
//fill it somehow...
return result_array;
}
And then I set it like:
int* my_array = malloc(sizeof(int)*10);
my_array = get_filled_array();
Does the memory of my_array gets removed or what is happens? I quess it is wrong this way but was just wondering. I quess if I want to do it like this, I should create an temporary array, get the returned array of (get_filled_array() and then set my_array and the temporary equal, so I can later free the memory of both?