c++ - 指针如何变化?

标签 c++ pointers

我无法在下面的代码中找到指针变化原因的解释。

struct node{
    int val;
    node *left;
    node *right;
}*root;

int main() {

    node *tmp = (node *)malloc(sizeof(node *));
    tmp->val = 5;
    tmp->left = NULL;
    tmp->right = NULL;
    root = tmp;


    node *t = (node *)malloc(sizeof(node *));
    cout<<"earlier: "<<&root->right<<" "<<root->right<<endl;
    t->val = 4;
    cout<<"after: "<<&root->right<<" "<<root->right<<endl;
    t->left = NULL;
    t->right = NULL;
    root->left = t;

    return 0;
}

输出是-

earlier: 0x7fb812404ac0 0x0
after: 0x7fb812404ac0 0x4

root->right 的值已经改变,不再是NULL

注意 - 我在我的 OSX g++ 编译器中遇到这个错误

Configured with: --prefix=/Applications/Xcode.app/Contents/Developer/usr --with-gxx-include-dir=/usr/include/c++/4.2.1
Apple LLVM version 6.1.0 (clang-602.0.49) (based on LLVM 3.6.0svn)
Target: x86_64-apple-darwin14.3.0
Thread model: posix

它在其他版本的 g++ 上按预期工作,如 http://ideone.com/tIEjU4 所示

我错过了什么?

最佳答案

这看起来像是未定义的行为,因为您在以下两行中写入分配太小的未分配内存。

node *tmp = (node *)malloc(sizeof(node *));
node *t = (node *)malloc(sizeof(node *));

相反,您需要为节点分配足够的资源。

node *tmp = (node *)malloc(sizeof(node));
node *t = (node *)malloc(sizeof(node));

正如@Mat 所指出的,您可能想在这里使用new,因为您已经将问题标记为c++

node *tmp = new node;
node *t = new node;

关于c++ - 指针如何变化?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30012063/

相关文章:

C - realloc 不反射(reflect)回 main

c++ - 为什么这个串行/调制解调器代码会弄乱我的终端显示?

c++ - C++ 中 const 的这两种用法有什么区别?

c++ - 关闭导致段错误的文本文件和 C++ 中 linux 下的 `glibc detected`

c - void* 类型转换为 char* 的增量失败

c - 为什么这个 C 程序会导致段错误(核心转储)?

c++ - 如何将带有指针数组的 C++ 类传递给 CUDA?

python - 我应该包括什么内容以进行boost.python扩展?

c++ - 段错误调用函数

c - 使用 malloc 分配动态内存