Racing Condition

Ángel González keisial@gmail.com
Thu Dec 20 08:14:00 GMT 2012


On 20/12/12 08:42, Ian Lance Taylor wrote:
> On Wed, Dec 19, 2012 at 11:16 PM, Hei Chan <structurechart@yahoo.com> wrote:
>> Let's say I have 2 threads trying to call the function below without any synchronization:
>>
>> void func(int x) {
>>     static char buffer[512];
>>     sprintf(buffer, "%d\n", x);
>>     printf(buffer);
>> }
>>
>> since buffer is static, and so obviously in some cases, there will be 2 threads trying to write to buffer, 1 writing to buffer and another reading from it, or 2 reading from it.
>>
>> Since it is just an array of char, besides content/stdout might not be what the callers should be expecting; will it cause the program to crash.
> This is not a GCC question.  It is a question about C, or about the
> threading model used by your OS.
>
> In principle this will be undefined behaviour and anything at all could happen.
>
> In practice the program will probably not crash, though exactly what
> it will print is completely unpredictable.  For example, there is no
> reason to think that it will only print numbers.
>
> Ian
If by chance buffer ended up with a %s being read (remember, its
contents are unpredictable) it could crash.

Just the sprintf+reading won't crash since 512 is much larger than the
maximum int to be printed, and it is initialised to \0 for being static.
If this had instead been a single pointer shared by the threads,
allocated from the heap, it could crash.




More information about the Gcc-help mailing list