c - 获取C函数的返回地址

标签 c function gcc memory-address built-in

我有一些 C 代码基本上看起来像

double* my_function(double* input) {
    double* output = (double*) malloc(...);
    // Do some stuff to output based on input
    return output;
}

假设我已经构建了一个名为 my_var_in 的数组,我的主要代码类似于

double* my_var_out = my_function(my_var_in);

这会创建内存,my_var_out 指向该内存;大多数时候这正是我想要发生的事情。但是,有时我只想更新 已经存在的内存。如果我写

double* my_var = ... ; // allocate and fill my_var as desired
my_var = my_function(my_var);

然后我失去了指向以前存在的内存的指针,因为 my_var 现在指向新分配的内存。我已经尝试过几种不同的想法来解决这个问题。

1) 我知道我可以通过将函数样式更改为类似的样式来实现它

void my_function(double* destination, double* source) {
    // Check if destination == source and update based on this

我以前开发过这种将目标指针作为输入参数传递并在那里更新它的风格;它在功能上运行良好,但我更喜欢输出指针的风格,并希望继续使用它进行开发。

2) 基于herehere ,看来 __builtin_return_address 函数可能会有一些用处。我想我可以使用此函数将输入地址与输出地址进行比较,并据此进行分配/更新。阅读文档后here , 我写了下面的测试

int* just_testing(int* in) {
    void* ptr = __builtin_return_address(0); // the return address of just_testing
    printf("Input address: %p\n", in);
    printf("From function: %p\n", ptr);

    return in;
}

int main(int argc, char** argv) {

    int* out = (int*) malloc(sizeof(int));
    out[0] = 2;
    printf("From main before call: %p\n", out);
    out = just_testing(out);
    printf("From main after call: %p\n", out);

    return 0;
}

这给了我输出

From main before call: 0x19b2010
Input address: 0x19b2010
From function: 0x4011f1
From main after call: 0x19b2010

不幸的是,__builtin_return_address 的结果与接收函数返回值的变量地址不匹配,这出乎我的意料。

为什么地址不一样?除了我在此处列出的两种方法之外,我也欢迎任何关于不同方法的建设性建议。

最佳答案

最干净的解决方案是有两个独立的函数:

#include <stdlib.h>
#include <string.h>

void compute_inplace(double *data) {
    data[0] *= 2;
}

double *compute_copying(const double *input) {
    double *output = malloc(sizeof *output * N);
    if (output == NULL)
        return NULL;

    memcpy(output, input, sizeof *output * N);
    compute_inplace(output);
    return output;
}

请注意,复制函数将其参数作为一个指向 const 的指针,如果您不小心将只读内存区域传递给它,这会有所帮助。

关于c - 获取C函数的返回地址,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40756632/

相关文章:

c - OpenMP time 和 clock() 给出了两个不同的结果

c - 这段将两个数字相乘的代码有什么问题?

c - scanf() 将换行符保留在缓冲区中

c - C 中全局变量的可见性/作用域是什么?

mysql - 如何在mysql函数中返回

c - 尽管为 libusb-1.0 指定了 -l 标志,但 gcc 链接器错误

c++ - 去修饰的 C++ 符号的歧义

java - Azure函数:Java How to accept content-type of application/xml then convert it to a POJO

C 编程传递字符函数

c++ - 在没有优化但当前上下文中仍然没有局部变量符号的程序上使用 gdb 进行调试