This is my code: there is array of size 5. and I allocating memory to the pointer p using malloc function. here I want to know what happen after re-allocating the memory to same pointer and after free the pointer than what happen. and when my if condition is true or when it's going to execute.
int main()
{
int array[5] = {2, 5, 3, 10, 9};
int *p = (int*) malloc (sizeof (int));
*p = 5;
if (-1)
{
p = (int *)malloc(sizeof (int));
*p=6;
}
array[0] = *p;
free(p);
for (int i = 1; i < 5, i )
array[i] = array[0];
return 0;
}
CodePudding user response:
Memory is not allocated “to a pointer.”
A pointer is simply a variable that holds an address, the same way an int
is a variable that holds an integer value (within a range).
Given some int x = 3;
, when the program executes x = 8;
, nothing is done with the 3 that is in x
before the assignment except to overwrite it. It is gone, and there is a new value in x
.
Similarly, when a new value is assigned to a pointer, nothing is done with its old value except to overwrite it. The old value is gone, and there is a new value in the pointer.
After int *p = malloc(sizeof *p);
, p
contains the address of the memory that malloc
allocated, assuming it was successful.
This memory is not “allocated to the pointer.“ It is not bound in any way to the pointer. We could then do int *q = p; int *r = p; int *s = p;
, and we would have four pointers all pointing to the same address, and they would be identical. None of them would have any particular claim on the memory.
Alternately, after int *p = malloc(sizeof *p);
, we could do p = malloc(sizeof *p);
, and this would store a new address in p
. The old address is overwritten. The allocated memory is still allocated, because nothing freed it. But the program has lost track of its address.