c++ malloc() keeps assigning to same memory addres

2019-08-28 00:15发布

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

3条回答
疯言疯语
2楼-- · 2019-08-28 00:48
cout << &new_etc << endl;

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:

cout << new_etc << endl;

where you print the content of new_etc, i.e. the address that malloc returned.

Now, since you are freeing this memory after each iteration, you may get different addresses as well as the same one - after all, if you freed the memory malloc gave you in the past, it means that it can be reused.

查看更多
forever°为你锁心
3楼-- · 2019-08-28 00:54

To print the address of a pointer, drop &:

cout << &new_etc << endl;
        ^

It prints the address of pointer new_etc, not the address where new_etc points to. The address of new_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.

查看更多
Explosion°爆炸
4楼-- · 2019-08-28 00:56
new_etc = (node*) malloc(sizeof(node));
...
free(new_etc);

Why shouldn't malloc return the same block next time round, if you freed 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?

查看更多
登录 后发表回答