4

I'd like to know if my program could make a race condition or not? If so, please give me an example, because I can't see anyone.

#define STRING_SIZE 1024
char *string; 
int main(int argc,char**argv){
 int length; 
 if(argc != 2) return ;
 length = strlen(string);
 strncpy(string+length,argv[1],STRING_SIZE,STRING_SIZE-length);
return 0;

}

what if i make a lock ? does this correct the problem ?

#define STRING_SIZE 1024
int lock;
char *string; 
int main(int argc,char**argv){
 int length; 
 while(lock != 0){}
 lock = 1;
 if(argc != 2) return ;
 length = strlen(string);
 strncpy(string+length,argv[1],STRING_SIZE,STRING_SIZE-length);
 lock = 0;
 return 0;
}
mins
  • 6,478
  • 12
  • 56
  • 75

1 Answers1

3

Race conditions occur if there are more more than one thread of execution in a process and they all tend to(have access to) operate (read/change) a shared variable.

In your case there is only thread in execution - main though the char *string is declared global.Hence no race condition.

To see race conditions in actions, create threads using pthread. In the thread function access/change the shared variables randomly ( the `char* string in your example). Print the values during the execution. You will see the impact.

Note: In your example, there isn't memory allocated for char *string. Doing strlen on that is incorrect.

Prabhu
  • 3,443
  • 15
  • 26