简体   繁体   English

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

[英]C: malloc'ed pointer changes location after being returned from function?

I have a function that creates and returns a double* , but the location seems to change after I return it from the function, which leads to a seg fault. 我有一个创建并返回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;
}

This gets called from 这是从中调用的

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

Which prints 哪个打印

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

In every case, the address inside the function is 0x100000000 greater than the address outside the function. 在每种情况下,函数内的地址都比函数外部的地址大0x100000000。 What am I missing here? 我在这里错过了什么?

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. 在这种情况下,编译器会假定函数返回int ,因此生成错误的代码来处理返回值。

If so, there should be at least two error or warning messages generated - check your compiler output. 如果是这样,应该至少生成两个错误或警告消息 - 检查编译器输出。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM