c ++ malloc()保持分配到相同的内存地址 [英] c++ malloc() keeps assigning to same memory address

查看:349
本文介绍了c ++ malloc()保持分配到相同的内存地址的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图使用内存来迭代地创建节点。我的代码当前只是说,它去的地址,并不实际上尝试在链接列表中的链接。

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.

以下是节点的代码:

struct node {
  int num;
  node *next;
};

下面是 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



<输出:

EDIT

Output:

0xcff010
0xcff030
0xcff050
0xcff070
0xcff090
0xcff0b0
0xcff0d0
0xcff0f0
0xcff110
0xcff130


推荐答案

new_etc = (node*) malloc(sizeof(node));
...
free(new_etc);

为什么不应该 malloc 如果你免费已经下一次
在缓存中应该是热的,所以可能是最好的选择。

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?

这篇关于c ++ malloc()保持分配到相同的内存地址的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆