简体   繁体   中英

An integer increments strangely in c

Ok, here is the piece of code where I found it strange:

printf("di consumerthread : mulai isi data, itmsg = %d\n",itmsg);                               
msgq->data[itmsg]=rec_data;
printf("di consumerthread : selesai isi data, itmsg = %d\n",itmsg); 

What I found strange is the output:

di consumerthread : mulai isi data, itmsg = 42
di consumerthread : selesai isi data, itmsg = 98

How come the itmsg variable suddenly changes from 42 to 98 after this line?

msgq->data[itmsg]=rec_data;

Can anybody please tell me how to solve this problem and the cause of this strange output?

Perhaps msgq->data[itmsg] is an alias for itmsg. It could happen. If you inherited this code run a bounds checker on it.

What is the size of the data array? Are you writing off the bounds of it?

It is possible that itmsg is being overwritten by the assignment of rec_data to msgq->data[itmsg]. If they are declared near to each other, this is very possible.

无法仅基于问题中的信息就无法确定,问题可能是多个线程同时访问同一内存位置( msgq->data[itmsg] ),而没有任何适当的同步。

Do you have two or more threads that both use the itmsg variable? There's nothing in your code snippet that would change the value of that variable, so it looks like it must be another thread that's changing it.

If you're using threads, you'll need to protect any data that they share with a mutex.

Ok, I finally found what's wrong

Sorry if I dont give you enough info because my head is in a mess to explain it in detail..

So, what I did to solve it is: changing all type of global variable, including itmsg, to static and all type of procedure and function which use the global variable to static

and it solved all of my problem!

though I still dont know what's static function..

Thanks for all of your help! :D

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM