0

I have a strange problem, which I have not experienced till now.

I create two threads, and each thread basically opens a a FILE* to write some data onto the disk. Now, the writing part itself does not cause runtime problems (the output seems to be corrupted though), but all hell breaks loose when I close the two different FILE* in these two separate threads.

I see that one thread has _IO_buf_base pointing to 0x7ffff66d3000 whereas in the other thread _IO_write_end points to 0x7ffff66d3000. Maybe this is the reason that fclose thows up:

*** Error in `/home/raid/Documents/Temp/TemperatureMonitoringC/Debug/TemperatureMonitoringC': free(): invalid next size (normal): 0x00007ffff0000950 ***

*** Error in `/home/raid/Documents/Temp/TemperatureMonitoringC/Debug/TemperatureMonitoringC': free(): invalid next size (normal): 0x00007ffff0003540 ***

I am pretty sure that I am not the first person the have messed it up. Can anyone help? I could not find clear enough referenced on Google.

Debugger screenshots for both threads:

Debugger Window: Thread 1

Debugger Window: Thread 2

alk
  • 69,737
  • 10
  • 105
  • 255
devendra rai
  • 135
  • 12
  • 1
    How are the `FILE*` variables declared and initialised? The relevant code seems necessary to understand what is happening. – alk Feb 10 '14 at 16:23
  • 1
    The error messages you show indicate corruption of the memory management. Try running the program using a memory checker like Valgrind: http://valgrind.org – alk Feb 10 '14 at 16:24
  • Thanks a lot for your comments. I did run the application through valgrind and it showed me memory corruption, although it was very cryptic about the cause. I found that the real reason (at least seems to be) that the threads did not synchronize properly and now that I fixed it, the error seems to have disappeared. However, for the life of me, I still cannot understand why would the code throw up when closing FILE*. The FILE* variable was function scoped, non-static and therefore, I did not expect that anything could go wrong. – devendra rai Feb 11 '14 at 09:38
  • 1
    When memory corruption happend most likely the code ran into undefined behaviour also, thus more or less anything could happen then. Just be happy you got to know Valgrind now, it will be you reliable fellow during upcoming debugging-sessions ... ;-) – alk Feb 11 '14 at 09:51
  • Thanks @alk. Hopefully, it gets better with experience. – devendra rai Feb 12 '14 at 22:22

1 Answers1

0

I am back with a possible cause:

I had threads in which I was independently malloc'ing memory and then free'ing it. I read here that free should be in exact reverse order as that of malloc calls.

Since threads are basically asynchronous, and there was no way of really enforcing the malloc-free call order.

Of course, I would want to know whether malloc-free call order is required across the threads.

Can someone at least confirm whether I thinking correctly?

Community
  • 1
  • 1
devendra rai
  • 135
  • 12