//Smart pointer structure with built-in length and blocksize
typedef struct SMPTR_H_VAR
{
UINT H_SMPTR_LEN;
UINT H_SMPTR_BSZ;
} SMPTR_H_VAR;
typedef struct SMPTR
{
void *MBLOC;
SMPTR_H_VAR *shv;
const UINT *const BLOCL;
const UINT *const BLOCSZ;
} SMPTR;
//Smart pointer strucure 'constructor'
SMPTR *_SMPTRC(UINT var_sz, UINT var_num)
{
/*
// SMPTR structure
//
// Memory block casted to void *
// SMPTR_H_VAR structure
// const UINT *const BLOCL variable, used as a reference length variable for the 'Memory block' above
// const UINT *const BLOCSZ variable, used as a reference size variable, 'in bytes', for the size of the 'Memory block' above
*/
//Creation and initialization is done dynamically, to prevent the rise of bad pointers.
SMPTR *s = (SMPTR *)malloc(sizeof(SMPTR));
SMPTR_H_VAR *shv = (SMPTR_H_VAR *)malloc(sizeof(SMPTR_H_VAR));
//SMPTR_H_VAR variables are set through the SMPTR pointer
s->shv;
s->shv->H_SMPTR_LEN = var_num;
s->shv->H_SMPTR_BSZ = var_sz * var_num;
s->MBLOC = malloc(var_sz * var_num);
s->BLOCL = &shv.H_SMPTR_LEN;
s->BLOCSZ = &shv.H_SMPTR_BSZ;
return s;
}
在此代码中,SMPTR 作为指针返回,我想将此变量作为非指针返回。这里我在动态内存中创建了一个结构,这样它就永远不会超出范围。这就是为什么到处都有很多指针的原因。
最佳答案
当您从函数返回对象时我看到的问题。
您在
_SMPTRC
中对malloc
进行了 3 次调用。弄清楚哪些代码负责释放这些内存非常重要。否则,您的代码将泄漏内存。调用函数将获得对象的二进制副本。您将有两个指向动态分配内存的
SMPTR
对象(shv
和MBLOC
)。您必须制定一个策略来释放它们指向的内存。调用函数将无法释放
_SMPTRC
中分配的s
内存。你会出现内存泄漏。通过使用s
对象而不是从malloc
获取内存的指针,可以轻松解决此问题。
如果您找出哪个代码块负责动态分配的内存,则可以解决这些问题。您只需要认识到这些问题即可。
关于c - 将动态创建的结构体作为非指针对象返回,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23877879/