本人现在有一个结构体
typedef struct
{
size_t *p;
size_t buf[2];
}xxMatStep;
typedef struct
{
int rows;
int cols;
xxMatStep step1;
}XxMat;
static void xxMatStep_Construct_Without_Param( xxMatStep *step1 )
{
step1->p = step1->buf;
step1->p[0] = step1->p[1];
}
static void xxMat_Construct_Without_Param( xxMat *mat )
{
mat->rows = 0;
mat->cols = 0;
xxMatStep_Construct_Without_Param( &mat->step1 );
}
static XxMat xxMat2( int rows, int cols, int step )
{
XxMat m;
xxMat_Construct_Without_Param(&m);
m.rows = rows;
m.cols = cols;
m.step1.p[0] = step;
m.step1.p[1] = 1;
return m;
}
本人现在调用xxMat2接口构造一个XxMat结构,发生了一些奇怪的事情,代码如下
XxMat cur_mat = xxMat2( 1280, 720, 1280 );
static void xxMat_DownSample( XxMat *src, XxMat *dst )
{
int sstep = src->step1.p[0];
int dstep = dst->step1.p[0];
//...
}
调用xxMat2后,调试查看cur_mat的成员,step1.p[0],step1.p[1]都是正常的数值,然后本人调用xxMat_DownSample(&cur_mat, &dst_mat)出了问题,下断点进入到xxMat_DownSample里,发现sstep即cur_mat的成员step1.p[0]的数值变乱了,VS2010 Debug模式下,sstep数值很大,是3435973836。
问一下这是哪里出了问题吗?
解决方案
100
原因是 xxMat2 里的 m 和返回的 xxMat 即 cur_mat 已经不是同一个 xxMat 了。
它在函数返回时被复制, m 所占用的空间被释放,但返回的结构体里还包含指向 m 的成员的指针,因此返回的结构体是不可用的。
它在函数返回时被复制, m 所占用的空间被释放,但返回的结构体里还包含指向 m 的成员的指针,因此返回的结构体是不可用的。