-2

Can I malloc the same variable multiple times in a loop, will it get a allocate it a new memory address?

int* var;
int i;
for(i = 0; i < 5; i++)
{
    var = (int*)malloc(sizeof(int));
}

Does this allocate a new space, this is not how I would actually use it, I would use in a situation where the address would be reassigned to a linked list so it could be freed and would not cause a memory address.

Cameron
  • 75
  • 1
  • 1
  • 6
  • 4
    Yes, you get a new allocation each time. And leak the previous ones. – Bo Persson Nov 13 '17 at 23:53
  • Yes, to avoid leakage, you must retain a pointer to the old value somewhere before reloading/reseating 'var'. as answered by @Unh0lys0da below, – Martin James Nov 14 '17 at 00:22
  • 1
    You are not "mallocing a variable". Your code allocates 5 distinct regions of memory, and you have lost the address of 4 of them. The address of the 5th is held in the variable `var`. – William Pursell Nov 14 '17 at 00:41

2 Answers2

2

Yes this is fine as long as you do something with the variable before reassigning. And with 'do something' I mean: make a copy of the pointer before reassigning it and call free on that copy later.

Unh0lys0da
  • 196
  • 8
0

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));
}
H.S.
  • 11,654
  • 2
  • 15
  • 32