I'm trying to create "nodes" iteratively using memory. My code currently just says what address it goes to, and does not actually try to make the links in the linked list.
Here's the code for a node
:
struct node {
int num;
node *next;
};
Here's the code for malloc()
node *etc = (node*) malloc(sizeof(node));
etc->num = 1;
etc->next = NULL;
cout << etc << endl;
for (int i=2; i<=10; i++) {
node *new_etc;
new_etc = (node*) malloc(sizeof(node));
cout << new_etc << endl;
}
EDIT
Output:
0xcff010
0xcff030
0xcff050
0xcff070
0xcff090
0xcff0b0
0xcff0d0
0xcff0f0
0xcff110
0xcff130
Here you are printing the address of the variable
new_etc
, i.e. the location of memory where the pointer is stored, not the address to where it points. What you want is:where you print the content of
new_etc
, i.e. the address thatmalloc
returned.Now, since you are
free
ing this memory after each iteration, you may get different addresses as well as the same one - after all, if you freed the memorymalloc
gave you in the past, it means that it can be reused.To print the address of a pointer, drop
&
:It prints the address of pointer
new_etc
, not the address wherenew_etc
points to. The address ofnew_etc
is same and will not change after assigning a pointer to it.After edited question : See this live code which shows different addresses. So, you're output is not related to the code you're showing us.
Why shouldn't
malloc
return the same block next time round, if youfree
d it already? It should be hot in cache, so may well be the best choice.If you don't
free
the memory, and you fix your logging, what happens?