在struct中释放数组后的SIGABRT

时间:2012-04-28 10:38:20

标签: c memory struct free sigabrt

我有一个函数,它返回一个struct数组,如下所示:

my_struct * testFunction(int pSize, int pW_size) {
   struct my_struct* struct_array = (my_struct*) malloc(sizeof(my_struct)*pSize);
   for(int i=0; i<pSize; i++) {
          struct my_struct test;
          test.w_i = (double*) malloc(sizeof(double)*pW_size);
          struct_array[i] = test;
   }
   return struct_array;
}

调用函数并使用数组后,我释放内存:

struct my_struct * T;
T=testFunction(theSize,wSize);
.....
for (int i = 0; i < theSize; i++)
    free(T[i].w_i); // I have a SIGABRT in this line
free(T);

所以我在注释的代码行中有SIGABRT。

glibc detected *** ./exec_main: double free or corruption (!prev): 0x0000000013f74720 ***
======= Backtrace: ========= /lib/libc.so.6[0x30004762f6] /lib/libc.so.6(cfree+0x6c)[0x300047ac6c]

感谢您的帮助。

1 个答案:

答案 0 :(得分:0)

my_struct * testFunction(int pSize, int pW_size)
{
   return (my_struct *)malloc((sizeof(my_struct) + sizeof(double) * pW_size) * pSize);
}