At the very least, ptr
could be declared as volatile
; but that is not enough. You really want atomic operations. With C11 you have <stdatomic.h>
standard header.
And recent GCC has atomic builtins that you should use. Both the access and the writing (in "your other thread") of your ptr
should be atomic!
Actually (without using atomic operations) the behavior that you would observe is undefined behavior and could vary a lot (with different processors, different compilers, etc...).
Sadly, on many x86 processors, you may not notice that UB
You need the compiler to enforce/use cache coherence by emitting particular machine instructions.
You could also use condition variables with mutex locks, or some semaphore.
With a recent GCC (at least 4.9) you might consider compiling with -fsanitize=thread
and/or -fsanitize=address
(for debugging) if your target processor supports that.
BTW, your memory corruption might be completely unrelated. You could consider using valgrind
which is supported on many platforms (it is better to compile your program with -g
and you could try to compile with gcc -O1 -g
if you wanted to).
I also recommend using recent tools (recent version 4.9 of GCC -in september 2014-, recent binutils, recent gdb, recent libc, recent kernel....)