Reputation: 788
I have made a program that is based on a linked list with nodes which is linked together with a pointer. Every node holds an integer that stores a number and a pointer to the next node. The queue follows FIFO.
EVerything seem to work perfect! I can add new nodes to the queue and I can delete nodes - all in a FIFO-order.
The program is about dynamic memory-allocation (use the malloc and free library functions)
So what is my question then? The question is how memory-works, i.e. when these nodes is stored on the heap - why are the nodes stored in the following manner.
1 (205888)
2 (206032)
3 (206888)
4 (206904)
5 (215896)
6 (215912)
7 (215928)
This is the output from the program. The first is the stored integer and withing parenthesis is the address to the node.
So - have a look att the address of node 5 and compare it to earlier nodes - Something seem to be happening in memory - its a jump in thousand if bytes - from 206904 to 215896.
Why is it such a jump here? ANd what implication does it have? Could it really be a memory leak? or is it in this manner OS and the compiler organize memoryr-allocation???
Upvotes: 1
Views: 2424
Reputation: 715
I'm assuming you're using malloc to allocate memory when you need to create a new node. At a high level, malloc just gives you a block of memory that can hold the size of data you ask for. Since it just finds whatever block of memory is available, the memory locations malloc returns on different calls aren't guaranteed to be anywhere near each other.
Just a small update:
My point is, as long as you free the memory and don't leave/lose pointers, you'll be fine. The jumps in memory locations aren't anything to be worried about. That's normal for memory allocation, and they aren't an indication that anything is going wrong with your program.
Upvotes: 2
Reputation: 618
Everything is just fine... The is nothing as such that the new block will get a place or address near the previous one.All we know is that previous node contains the address of the first node. Dynamic memory allocation is not contagious. For e.g the malloc function will request a block of memory from the heap. If the request is granted, the operating system will reserve the requested amount of memory. However if u would have used array the addresses would have been as expected by you.
Upvotes: 0