我如何在C对象方法在C:内存泄漏
正确地实现对象的问题是,我从方法更容易出现内存泄漏返回对象其实不是,例如,从来没有返回一个对象,在参数列表中通过引用来做这件事?
extern void quaternion_get_product(Quaternion * this, Quaternion * q, Quaternion * result);
这样的malloc()
通话仅在构造函数中完成,所以它更容易控制。
我是新来的这种封装在C中,所以我不知道这是否会解决我的问题的方式。我只想让我的代码具有可扩展性,并且我发现如果我继续这样做,内存泄漏将会遍布全球,并且调试将非常困难。它通常如何接近?我的代码是否正确?
我的问题是,如果我有这样的:
Quaternion p = *quaternion_create(1, 0, 0, 0);
Quaternion q = *quaternion_create(1, 0, 1, 0);
Quaternion r = *quaternion_create(1, 1, 1, 0);
Quaternion s = *quaternion_create(1, 1, 1, 1);
p = *quaterion_get_product(&p, &q); // Memory leak, old p memory block is not being pointed by anyone
Quaternion t = *quaternion_get_product(&q, quaternion_get_product(&s, &r));
内存泄漏是存在于由任何现有的指针嵌套函数调用时,中间存储器块不被指出,不能调用quaternion_destroy
头文件:
#ifndef __QUATERNIONS_H_
#define __QUATERNIONS_H_
#include <stdlib.h>
typedef struct Quaternion Quaternion;
struct Quaternion {
float w;
float x;
float y;
float z;
};
extern Quaternion *quaternion_create(float nw, float nx, float ny, float nz);
extern void quaternion_destroy(Quaternion *q);
extern Quaternion *quaternion_get_product(Quaternion *this, Quaternion *q);
extern Quaternion *quaternion_get_conjugate(Quaternion *this);
extern float quaternion_get_magnitude(Quaternion *this);
extern void quaternion_normalize(Quaternion *this);
extern Quaternion *quaternion_get_normalized(Quaternion *this);
#endif
实现文件:
#include "quaternion.h"
#include <math.h>
Quaternion *quaternion_create(float nw, float nx, float ny, float nz) {
Quaternion *q = malloc(sizeof(Quaternion));
q->w = nw;
q->x = nx;
q->y = ny;
q->z = nz;
return q;
}
void quaternion_destroy(Quaternion *q) {
free(q);
}
Quaternion *quaternion_get_product(Quaternion *this, Quaternion *p) {
Quaternion *return_q = quaternion_create(
this->w * p->w - this->x * p->x - this->y * p->y - this->z * p->z, // new w
this->w * p->x + this->x * p->w + this->y * p->z - this->z * p->y, // new x
this->w * p->y - this->x * p->z + this->y * p->w + this->z * p->x, // new y
this->w * p->z + this->x * p->y - this->y * p->x + this->z * p->w
);
return return_q;
}
Quaternion *quaternion_get_conjugate(Quaternion *this)
{
return quaternion_create(this->w, -this->x, -this->y, -this->z);
}
float quaternion_get_magnitude(Quaternion *this) {
return sqrt(this->w * this->w + this->x * this->x + this->y * this->y + this->z * this->z);
}
void quaternion_normalize(Quaternion *this) {
float m = quaternion_get_magnitude(this);
this->w /= m;
this->x /= m;
this->y /= m;
this->z /= m;
}
Quaternion *quaternion_get_normalized(Quaternion *this) {
Quaternion *r = quaternion_create(this->w, this->x, this->y, this->z);
quaternion_normalize(r);
return r;
}
有你想仿效C对象的理由? C++会不会更容易? –
我根本不使用malloc/free,主要是因为性能较低,因为malloc/free是相当昂贵的操作。 –
只是一面评论。我怀疑你正在实现四元数来对性能敏感的东西进行数学运算。不断的malloc会绝对破坏你的表现。如何避免内存泄漏并且不会同时破坏您的性能的一个体面的答案是:不要malloc。不惜一切代价避免malloc,让用户处理分配和释放。 – Art