#include<stdio.h>
typedef struct test{
int a;
int b;
}TEST_ST;
typedef struct hello{
int m;
TEST_ST *v;
}SOURCE_DATA;
SOURCE_DATA *creat_data2()
{
SOURCE_DATA *data_m=NULL;
data_m = calloc(1,sizeof(SOURCE_DATA));
data_m->v = malloc(sizeof(TEST_ST));
printf("data_v addr = %p\n",data_m->v);
printf("data_v0-a addr = %p\n",&(data_m->v[0].a));
printf("data_v0-b addr = %p\n",&(data_m->v[0].b));
printf("data_v1-a addr = %p\n",&(data_m->v[1].a));
printf("data_v1-b addr = %p\n",&(data_m->v[1].b));
printf("data_v2-a addr = %p\n",&(data_m->v[2].a));
printf("data_v2-b addr = %p\n",&(data_m->v[2].b));
printf("data_v3-a addr = %p\n",&(data_m->v[3].a));
printf("data_v3-b addr = %p\n",&(data_m->v[3].b));
printf("data_v4-a addr = %p\n",&(data_m->v[4].a));
printf("data_v4-b addr = %p\n",&(data_m->v[4].b));
data_m->m = 2;
data_m->v[0].a =3;
data_m->v[0].b =4;
data_m->v[1].a =3;
data_m->v[1].b =4;
data_m->v[2].a =8;
data_m->v[2].b =7;
data_m->v[3].a =4;
data_m->v[3].b =4;
data_m->v[4].a =4;
data_m->v[4].b =5;
return data_m;
}
void creat_data(SOURCE_DATA *data)
{
SOURCE_DATA *data_tmp=NULL;
data_tmp = creat_data2();
memcpy(data,data_tmp,sizeof(SOURCE_DATA));
// if(data_tmp->v)
// {
// free(data_tmp->v);
// data_tmp->v = NULL;
// }
if(data_tmp)
{
free(data_tmp);
data_tmp = NULL;
}
}
int main(void)
{
SOURCE_DATA data={0};
creat_data(&data);
printf("end data m = %d\n",data.m);
// printf("data v = %p\n",data.v);
printf("end data0 = %d\n",data.v[0].a);
printf("end data0_ = %d\n",data.v[0].b);
printf("end data1 = %d\n",data.v[1].a);
printf("end data1_ = %d\n",data.v[1].b);
printf("end data2 = %d\n",data.v[2].a);
printf("end data2_ = %d\n",data.v[2].b);
printf("end data3 = %d\n",data.v[3].a);
printf("end data3_ = %d\n",data.v[3].b);
printf("end data4 = %d\n",data.v[4].a);
printf("end data4_ = %d\n",data.v[4].b);
// free(data.v);
}
请教个C问题没有想明白。请大家给个解答。
这个代码里的第19行,data_m->v = malloc(sizeof(TEST_ST)),这句只申请了8个字节的空间,为什么v对应的数组超出8个字节后还能正常存储数值啊?
这个data_m->v 申请的内存,怎么样释放?若是在第59行释放,只能释放申请的8个字节,但为什么v[1]到v[4]还能有数据?