Can I malloc the same variable multiple times in a loop, will it get a allocate it a new memory address?
malloc
allocates a block of size bytes of memory, returning a pointer to the beginning of the block. So, in this for
loop:
for(i = 0; i < 5; i++)
{
var = (int*)malloc(sizeof(int));
}
in every iteration, malloc
is allocating a new block of memory and returning a pointer to the beginning of the block which is getting assigned to var
variable. But you have mentioned in the question - "address would be reassigned to a linked list.." so, assuming you are keeping the allocated memory references somewhere.
This is as good as this:
int somevalue;
for(i = 0; i < 5; i++)
{
somevalue = i+10; //Just assigning a value to variable
}
In every iteration, a new value is getting assigned to somevalue
variable. After loop finishes, the variable somevalue
will have the value assigned in the last iteration of the loop.
Does this allocate a new space..
Yes, as long as malloc
is successful.
Additional note:
Do not cast the malloc
return. Check this.
So, you should:
for(i = 0; i < 5; i++)
{
var = malloc(sizeof(int));
}