How to make sure that different dynamic memory is allocated to the same pointer when using while loop?

Pages: 12
Here is my question:

How to use a while loop to allocate different dynamic memory address to the same pointer?

For example, there is a pointer named "Creator"

Then i use this code

 
int *Creator = new int;


to allocate a new dynamic memory address for the Creator

However, whenever i use a while loop to keep allocating the dynamic memory to Creator, it stills allocate the same memory to the Creator

How to make sure that for every loop, my dynamic memory address allocated to the Creator will be different each time?

Any help in any form is much appreciated,thank you in advance


Edit:Here is my code, sry for not putting it here yesterday, this should make my question more readable

1
2
3
4
5
6
7
8
9
10
11
12
13
int main()
{
	int i = 0;
	int* p = new int;
	while (i <= 5)
	{
		delete p;
		p = new int;
		cout << p << endl;
		i++;
	}

}


And this is the output:

00B69B50
00B69B50
00B69B50
00B69B50
00B69B50
00B69B50


Last edited on
What the fuck are you babbling about?
Every time that you assign dynamic memory to the Creator pointer you are overwriting the previous pointer. This does not mean that the data in the previous pointer is being overwritten, but is now orphaned. If this is done in a loop it is called a memory leak. (Basically you will run out of memory, hopefully your program will crash gracefully rather than causing the computer to crash).

There are several ways to do what you're asking. I think what you really want would be to allocate an array of int pointers. It's very important to call delete on the dynamic array when you are done using it.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
#include <iostream>
int main()
{
    int value;
    std::cout << "Enter a number to allocate: ";
    std::cin >> value;
    int * creator = new int[value];

    for(int i = 0; i < value; i ++)
    {
        creator[i] = i;
    }
    for(int i = 0; i < value; i ++)
    {
        std::cout << creator[i] << std::endl;
    }
    delete [] creator;
}


( http://cplusplus.com/reference/stl/ ) -> It is very highly recommended that you learn how to use vectors, lists, sets and other containers that are self-managed rather than managing raw dynamic pointers, but sometimes they can be convenient.
Last edited on
^^ This does not make a lot of sense.
answer 1, guessing at what you are asking:
while(whatever)
{
int *ip = new int;
something();
delete ip;
}
if you have that sort of loop, you CANNOT force the machine not to give you the same pointer every iteration. If the compiler has any sense, it ignores the new and delete and just recycles it (I am not sure compilers can make this call, though, pretty sure they do not). If it does what you told it blindly, it may still reuse the value depending on how the memory management on the system works: you ask for memory, I give you location 1234, the next available slot. You give 1234 back to me. you ask for memory, 1234 is the next available slot, here you go...

answer 2
it should be different if you don't delete it, and just leak it away. This is bad code, but you could do it for a study.

answer 3)
you can force it to be different if you combine 1 and 2 by storing the pointer to delete later, but recycling the one that gets newed each iteration.


whenever i use a while loop to keep allocating the dynamic memory to Creator, it stills allocate the same memory to the Creator

That's not possible unless you're returning the memory that was allocated within the loop.

If you are returning the memory within the loop, then as jonin told you you have no way to prevent the same memory from being allocated in the next iteration of the loop. In fact it's highly like that the runtime WILL allocate the same block of memory the next time through the loop.

Since you haven't shown your code for the loop, we can't know what is happening,
If the compiler has any sense, it ignores the new and delete and just recycles it
It's called "allocation elision" and Clang does it.
Last edited on
Sorry guys for not putting my code when asking yesterday

I dont know why even i deleted the memory allocated to the pointer and allocate another dynamic memory it sills gives me the same dynamic memory

Is this even possible?

Why I need to do so is because I need to store different data in different dynamic memory address for each while loop

> I need to store different data in different dynamic memory address for each while loop

What is the actual problem that you are trying to solve?
For example:

1
2
3
4
5
6
7
8
9
10
11
int i = 0;
	int* p = new int;
	while (i <= 5)
	{
		*p = i;
		cout << p << endl;
		cout << *p << endl << endl;
		i++;
		delete p;
		p = new int;
	}




I want the p, which is the dynamic memory address be different for each loop

But the output gives me this:

012E9A00
0

012E4F80
1

012E4F80
2

012E4F80
3

012E4F80
4

012E4F80
5



As you can see, for 2nd to 6th iteration, the address stored into the pointer is always the same, and what i want to do is make them different!

Have I made myself clear enough? Coz I cannot think of a better way to ask questions due to my poor english
Last edited on
> Have I made myself clear enough?

No.

> the address stored into the pointer is always the same, and what i want to do is make them different!

Why do you want the addresses to be different? What is wrong if an address that is no longer in use is recycled?
Why do you want the addresses to be different? What is wrong if an address that is no longer in use is recycled?


Coz Im curious about it! I wonder why even when I am using the word 'new' but the compiler still gives me the same dynamic memory address instead of giving me different blocks of memory?

Also, since I just started learning c++, understanding these will make my learning journey a bit smoother coz I get to know how these things work
Last edited on
> Coz Im curious about it!

A common implementation of the allocation mechanism could be:

a. the allocator keeps a list of free (available for allocation) blocks (chunks of memory of a particular size range)

b. when an allocation needs to be performed (say with new), it looks into the free list, and if a free block is available it is removed from the free list (allocated). An implementation may pick up the most recent item that was added to the free list (this gives better cache performance).

c. when a deallocation is performed (with delete), the block that is released is added back to the free list.
lets see...
the operating system is a waiter at your favorite food place.
you sit down and ask for a NEW menu.
the waiter gives you the first one he has available, menu number 1000.
you look at it, and give it back.
Then you ask for a menu again. The first one he sees is number 1000; someone just handed it to him.
you look at it and give it back.
then you ask for the menu again.
the waiter happily gives you the first one available, and ... you guessed it, its # 1000 again.

this is just ONE of MANY possible ways the waiter could behave. He could also put the one you touched in a sanitize bin because of covid, and hand you a clean one each time. This is out of your control, though -- you can't tell him which menu to give you, just that you want to see one. He decides which one to give you!

Its not totally unheard of for a programmer to write their own memory management system in a large program, or you could have to work on something like an OS or disk file management or something that uses the same ideas. Its good to study this at some point, at least a little bit. But if you are just playing with pointers, you really do not care what address you get: the OS has promised that you can use it until you give it back, and that it is safe and usable for you. The number and how it was selected only matter if you want to study memory management and operating system concepts in depth (its fine if you want to do that).

The only advice I will give is this: focus your studies. Either go learn c++, or learn about operating system design, but do not try to do both at once. HOW this works is not important to learn C++.
Last edited on
The allocator provided by the standard library of a programming language would typically not go to the operating system for each and every allocation; it implements a sub-allocation scheme.

K&R in '8.7 Example - A Storage Allocator' in 'The C programming language (2nd edition)':
The function morecore obtains storage from the operating system. The details of how it does this vary from system to system. Since asking the system for memory is a comparatively expensive operation. we don't want to do that on every call to malloc, so morecore requests at least NALLOC units; this larger block will be chopped up as needed.
Either way, something handles the allocation and that detail is not essential for regular use of C++. There is much to learn way before one has to implement a custom allocator scheme.
Ohhhhh so that means I'm overthinking isn't it......
May be; but that (curiosity in a programmer) is a good trait. Particularly with C++, a language that is strongly biased in favour of programmers who are willing to think for themselves.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
#include <iostream>
using namespace std;
 
int main(){	
	int *p;
	int *arr[5];
	for(int i=0; i<5; i++){
		p=new int;
		cout<< p << "\n";
		delete p;
		arr[i] = new int;
	}	
	for(int i=0; i<5; i++){
		delete arr[i];
	}
	
}


output in gcc compiler:
0x5557e899be70
0x5557e899cea0
0x5557e899cec0
0x5557e899cee0
0x5557e899cf00

but its not working in clang. its too over optimized for this.
Define "not working".
Is this what you meant?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
#include <iostream>
using namespace std;
 
int main(){	
	int *p;
	int *arr[5];
	for(int i=0; i<5; i++){
		p=new int;
		cout<< p << "\n";
		arr[i] = p;
	}	
	for(int i=0; i<5; i++){
		delete arr[i];
	}
	
}
If you release the pointer you printed there's nothing preventing the allocator from giving it to you again.
Pages: 12