首页 > 解决方案 > 将整数分配给指针时出现分段错误

问题描述

我正在尝试将我的节点值分配给一个指针,但是当代码运行时 gdb 给了我分段错误。我能做些什么?

void biggerPotion(No* node, int bottleSize, int *aux){
        if(node == NULL)
            return;
        maiorPocao(node>left, bottleSize, aux);
        maiorPocao(node->right, bottleSize, aux);
        if((node->value >=  garra) && (node-> value < *aux))
            *aux = node->value;      //here is the issue
    }

代码的其他相关部分是:

for(i=0; i< nBottles;i++){
        a = 1000;             //i declared that 
        biggerPotion(potions,bottleSize[i],&a);
    }

标签: pointerssegmentation-fault

解决方案


好的,因为错误的行是:

*aux = node->value;

那么要么aux是问题要么node是(因为它们是该行上唯一被取消引用的两个指针)。

if为了确定,我会在执行该块之前将它们都打印出来:

fprintf(stderr, "node is %p, aux is %p\n", node, aux);

考虑. node_ aux_ _ 您应该发布该顶级调用,包括您传入的任何变量的声明。biggerPortion

在任何情况下,您都可以通过简单地更改来测试:

*aux = node->value;

进入:

{
    int temp = node->value;
}

如果问题消失了,那么肯定是aux指针以某种方式出错了。确保您实际上是在传递一个指针,例如:

int myVar;
biggerPotion(rootNodePtr, 42, &myVar);

推荐阅读