Okay so, I have approx 3000 lines of C code that I wrote. When I compile it as a standalone application (macOS and Linux) it works perfectly.When I compile it as a shared object, and call it from another C program, again it works perfectly.
HOWEVER... when I try to use the SAME shared object from a PureBasic app (with OpenLibrary()) it behaves really strangely and usually crashes.
The bizarre thing is, nothing about the C code has changed. Literally the only change when I build it as a library, is that I rename the main() function (because shared objects aren't supposed to have one).
On Linux, valgrind reports no errors. No invalid reads, writes, or conditional movs/jmps.
I cannot seem to debug the PB calling code with valgrind, because it complains about a missing implementation for a syscall (or something like that). I'm guessing this is because PB's debugger uses "interesting" techniques.

To describe the error in more detail, it seems that certain C structs that should be all zeroes end up with "random" numbers in them. The values are different on each run of the program. Almost any libc call can corrupt my structs in weird unpredictable ways.
I've tried sprinkling dozens of printfs around the code, then running the working/nonworking versions of my app, and doing a "git diff" on the output. This enabled me to see the memory corruption happening in situ, but I could only find the effects, not the cause.
I'm at my wits' end as I've been debugging this for four days. I don't even know what to try next.
Does anyone have any advice? Any tools that might help?
Thanks in advance.