C:malloc'ed指针在从函数返回后改变位置?

时间:2016-04-04 19:50:10

标签: c pointers

我有一个创建并返回double*的函数,但是从函数返回后该位置似乎发生了变化,从而导致了seg错误。

void get_data_internal(double* data, int64_t* i, Factor* fctr) {
    if (fctr->factor_type == DATA_PT) {
        data[*i] = get_factor_data_pt(fctr);
        (*i)++;
    }
    else {
        stSetIterator* child_iter = stSet_getIterator(get_factor_children(fctr));
        Factor* child_fctr = stSet_getNext(child_iter);
        while (child_fctr != NULL) {
            get_data_internal(data, i, child_fctr);
            child_fctr = stSet_getNext(child_iter);
        }
    }
}

double* get_data(HierarchicalDirichletProcess* hdp) {
    int64_t data_length = hdp->data_length;
    double* data = (double*) malloc(sizeof(double) * data_length);

    int64_t i = 0;
    stSetIterator* base_fctr_iter = stSet_getIterator(hdp->base_dp->factors);
    Factor* base_fctr = stSet_getNext(base_fctr_iter);
    while (base_fctr != NULL) {
        get_data_internal(data, &i, base_fctr);
        base_fctr = stSet_getNext(base_fctr_iter);
    }

    printf("returning data at address %p\n", data);
    return data;
}

调用
double* data = get_data(hdp);
printf("receiving data at address %p\n", data);

打印

returning data at address 0x10c343000
receiving data at address 0xc343000

在每种情况下,函数内的地址都比函数外部的地址大0x100000000。我在这里缺少什么?

1 个答案:

答案 0 :(得分:2)

Perhaps there is no prototype in scope at the point of the call:

double* data = get_data(hdp);

In this case the compiler would assume the function returns int and so generate the wrong code for handling the return value.

If so, there should be at least two error or warning messages generated - check your compiler output.