Reputation: 1366
I'm reading this book for the second time: "C++ primer plus" and one thing caught my eye: https://i.sstatic.net/xZYUW.jpg
Often memory is represented like a linear block(1), say you allocate 2 new blocks of memory,"a" and "b" in (2) and then delete "a" in (3). The arrow is the pointer to free memory according to the book/tutorials. Now these are my questions:
EDIT: I'm trying to understand how memory allocation really works behind the scenes, so I would like to know into more detail what happens when I type: "int i=0;" or "while(running)".
Upvotes: 1
Views: 213
Reputation: 785
There are no pointers to free memory. Ultimately this is handled, and controlled by, the operating system. It could have already allocated the memory used by a
to another process at that point.
You can have as many pointers as you want (well, as many as you have memory for). And they can point to anything, whether they are pointing to used memory or not.
If you try to allocate more memory than the OS will give you, new will fail, resulting in an exception (std::bad_alloc
).
Upvotes: -1
Reputation: 6031
Dynamic memory allocation works a bit differently than you presented it in your question. If you allocate two blocks of memory separately, they aren't neccessarily next to each other. If you allocate them with the same new
statement (such as as part of a struct
or array) then later delete only one of them, then they would be adjacent, but that is a very odd thing to do.
Look at the syntax of new
:
int* a = new int;
The new
operator actually returns a pointer to the allocated memory, and stores it in the pointer a
. If you call it twice, you get two different pointers to two different blocks of memory.
If you're allocating with an array, then you get one pointer to the first element of the array. However, calling delete
doesn't get rid of the pointer, it gets rid of the thing that it points to. So if you were to delete the first element of a
(not the entire array) then attempting to access the memory at a
would produce undefined behavior, but accessing a[1]
would be just fine.
Upvotes: -1