2

I have a function which returns an array of struct as follows:

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;
}

After calling the function and using the array I free the memory:

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);

So I have SIGABRT in the commented line of code.

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

Thanks for helping me.

mtvec
  • 17,846
  • 5
  • 52
  • 83
saloua
  • 2,433
  • 4
  • 27
  • 37
  • 2
    I'll guess that there's something wrong in the `...` part of your code. – Mat Apr 28 '12 at 10:44
  • 3
    You probably wrote past the range of the array in the "...and using the array" part of your code. You can make sure that's correct by commenting out the ... part of code, and freeing right after allocation. Run valgrind to find the details. – Sergey Kalinichenko Apr 28 '12 at 10:45
  • 1
    This has nothing to do with your problem, but you could really do with using more informative variable names. You have `pSize`, pW_size`, `theSize` and `wSize`; all of these things are really not sizes but counts, the names give no indication of what they are counting, and `pSize` (to me at any rate) suggests "pointer to size", which is not at all what that variable is. `w_i` is apparently an array of `double`s. You can do better than this! – Gareth McCaughan Apr 28 '12 at 10:46
  • As for the actual problem, I agree with Mat and dasblinkenlight: the problem likely lies in the portion of the code that you haven't shown. – Gareth McCaughan Apr 28 '12 at 10:46
  • Actually this is not my real code. I Have just written an example to illustrate the problem. I thought that the problem could be caused by the fact that each struct is copied when I add it to the array of struct. In the portion of code that I haven't shown I make a call to a function that uses T as const. – saloua Apr 28 '12 at 10:52
  • @tuxworker: try to run your code like you posted it, without all the stuff between the allocation and the dealloc. It shouldn't fail. – Mat Apr 28 '12 at 10:55
  • 4
    Adding obligatory advice to [stop casting mallocs return type](http://stackoverflow.com/questions/605845/do-i-cast-the-result-of-malloc). – Anthales Apr 28 '12 at 10:57

1 Answers1

0
my_struct * testFunction(int pSize, int pW_size)
{
   return (my_struct *)malloc((sizeof(my_struct) + sizeof(double) * pW_size) * pSize);
}
Feo
  • 161
  • 6