c - 这个 C 代码会泄漏内存吗?

标签 c pointers memory-management memory-leaks

这是我的代码:

typedef struct {
    int x;
    int *t;
}vector;

vector fct (vector v){
    vector w;
    int i;
    w.x=v.x;
    w.t=malloc(w.x *sizeof(int));
    for (i=0; i<w.x; i++)
        w.t[i]=2*v.t[i];
    return w;
}


int main (){
    int i;
    vector v;
    v.x=2;
    v.t=malloc(2*sizeof(int));
    v.t[0]=1; v.t[1]=5;
    v=fct(v);
    for (i=0; i<2; i++)
        printf("%d \t",v.t[i]);
    puts("");
    free(v.t);
    return 0;
}

我很担心它是否会导致内存泄漏,以及万一发生内存泄漏我该如何解决。 哦,我知道如果我定义另一个 vector 让我们说 w,这样 w = fct(v) 它会解决问题,但我需要一种不同的方法,即使函数返回到原始 vector 也能工作的方法。

最佳答案

v.t=malloc(2*sizeof(int));

在这里,您将分配的内存分配给 v.t

v=fct(v);

然后在这里用 fct 返回的内容覆盖 v 的所有字段。这会丢弃 v.t 的旧值,从而导致内存泄漏。

main 末尾调用 free 释放在 fct 中分配的内存。

您可以通过保存 v.t 并在保存的指针上调用 free 来修复此泄漏:

vector v;
int *vt_sav;
v.x=2;
v.t=malloc(2*sizeof(int));
vt_sav = v.t;
v.t[0]=1; v.t[1]=5;
v=fct(v);
free(vt_sav);

关于c - 这个 C 代码会泄漏内存吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47683704/

相关文章:

c - 从结构体中的数组中减去

pointers - 如何检测接口(interface){}是否为指针?

objective-c - 为什么要保留静态变量?

c++ - 协调类、继承和 C 回调

c++ - 将 unsigned short 转换为 char

c - 在c中用#Define定义的函数

c++ - 变量的地址需要加载到内存中吗?

c++ - 如何将某个类的指针方法转换为指针函数?

使用链表创建矩阵

c - 当函数返回时,临时存储在 C 中如何工作?