Reputation: 1295
So I'm aware that this question is most likely asked before, but after near an hour of searching I decided to ask all the same. Pointing me to a dublicate question which has already been answered would really be appreciated.
Then, programming in basic C, I'm curious to what happens to the array-elements when changing its pointer to pointing something else? Is it safe, without first freeing it? For instance,
int main()
{
const int size = 3;
int *p_arr = malloc(size * sizeof(int));
for( int i=0; i<size; i++)
p_arr[i] = i;
int arr[size] = {0,0,0};
p_arr = arr; // safe!?
// What happens to the data previously allocated
// and stored in *p_arr? Should one first call,
// free(p_arr)
// and then reallocate ..?
}
Essentially, changing the pointer will leave the data {0,1,2} in memory. Is this okay?
Thanks alot for any help!
Upvotes: 2
Views: 97
Reputation: 1
The array{0,1,2}
is already in the memory,but you can't get it unless you point a pointer to the head address of the array again.
Upvotes: 0
Reputation: 399833
Nothing happens to the data, except that it becomes unreachable ("leaked") and thus the memory is forever wasted, it can't be used for anything else until your program terminates (typically).
Don't do this, it's very bad practice to leak memory.
You should free()
the memory when you no longer need it.
Also, the allocation can be written:
p_arr = malloc(size * sizeof *p_arr);
to remove the duplication of the int
type, and lock the size to the actual variable. This is at least somewhat safer.
Upvotes: 3