1

I'm working on a C program that involves threading within the pthread library, as well as using some mallocs. I was troubleshooting my program and finally got it to where it runs with no memory leaks, and no errors.... sometimes

When I run my executable with valgrind and the following flags: valgrind -s --leak-check=full -v --show-leak-kinds=all

I get the following output:

enter image description here

enter image description here

Same program. If I spam this command in the shell maybe 3/10 times its the "still reachable" text, and the rest of the times it says all my memory blocks were freed.

I'm wondering, how is this even possible? Is this a common occurence when it comes to programs with threading?

Edit: I noticed when I run into the still reachable error, I have 4 less frees than I'm supposed to. Why does this occur?

1 Answers1

0

This shouldn't happen for race-free code.

Valgrind itself runs single threaded. The guest running under Valgrind can still run multiple threads, but the way that they are run will be like a single CPU without thread pre-emption.

The most likely thing is that your code has a race, and depending on which threads/functions finish first memory may or may not get freed.

Paul Floyd
  • 5,530
  • 5
  • 29
  • 43
  • Not sure I follow. What exactly is race-free code? I do know that I have multiple threads running performing the same operation, and some threads get done much quicker than others. But how is it that sometimes the memory is not freed and sometimes it is? I just dont follow how that can happen – mistahwhite Oct 25 '22 at 09:44
  • 1
    @mistahwhite Race condition is when your outcome depends on which thread reaches some critical point first. Race-free code works same no matter how fast (relatively) individual threads run. – Agent_L Oct 25 '22 at 10:06