-1

How to prevent memory leaks in pthread? I am running a server client program where server has to execute a pthread program and pss the result to client. The client keeps asking for the command again and again until it is stopped. The result provided by server is true only in the first iteration but it is providing incorrect results from second iteration.

I tried to use pthread_join and pthread_exit to prevent memory leaks but still its showing incorrect results.

  • What kind of memory leak? Can you show the offending code and a valgrind summary? – David Ranieri Nov 27 '22 at 20:34
  • so its basically a matrix inversion pthreads program. In the client, i give the size of matrix as input and server takes it and executes the pthreads program and outputs a result. The server gives correct output first time when client requests, but when i applied a while loop, the second time client asks me to enter a command, the server is adding 0.01 to all the elements of matrix of previous output.Sorry, but i do not know how to use valgrind. – Spurthi Dantu Nov 27 '22 at 21:09
  • 2
    Each call to (m|c|re)alloc requires a call to `free`, that's the only way to prevent memory leaks. We can't help you without seeing some code. – David Ranieri Nov 27 '22 at 21:44
  • Your code is [probably] small enough to post it _entirely_ as a _single_ code block here. It should compile cleanly, be downloadable and runnable, and illustrate the memory leaks. – Craig Estey Nov 27 '22 at 22:06
  • Memory leaks are an issue arising from incorrect management of dynamically-allocated memory. `pthread_join()` and `pthread_exit()` deal with *thread* management, not (dynamic) memory management. You likely do need to use them appropriately, but they have nothing in particular to do with memory leakage. – John Bollinger Nov 28 '22 at 15:51

1 Answers1

-1

When you have concurrent threads, these are working in the same address room which means that they'll share their memory. So modifying the variable in the first thread will alter the variables in the next thread.

You probably initialized the variables correctly in the beginning which leads to correct results. But after your first run, these aren't initialized correctly anymore.

Start debugging by checking the initial conditions and comparing these between the first and the second run

0x7477
  • 3
  • 4
  • 1
    I don't see anything incorrect in this answer, but it is not responsive to the question posed. It would be appropriate as a comment on the question, but not as an answer. You will be able to leave such comments when you have gained a little more site reputation. – John Bollinger Nov 28 '22 at 15:47