views:

56

answers:

1

I have a threadMethod which shows in console robotMotorsStatus every 0.5 sec. But when I try to change robotMotorsStatus in changeRobotStatus method I receive an exception. Where I need to put locks in that program.

#import "AppController.h"

@implementation AppController
extern char *robotMotorsStatus;

- (IBAction)runThread:(id)sender
{
 [self performSelectorInBackground:@selector(threadMethod) withObject:nil];
}

- (void)threadMethod
{
 char string_to_send[]="QFF001100\r"; //String prepared to the port sending (first inintialization)
 string_to_send[7] = robotMotorsStatus[0];
 string_to_send[8] = robotMotorsStatus[1];
 while(1){
  [theLock lock];
  usleep(500000);
  NSLog (@"Robot status %s", robotMotorsStatus);
  [theLock unlock];
 }

}

- (IBAction)changeRobotStatus:(id)sender
{
 robotMotorsStatus[0]='1';
}
A: 
extern char *robotMotorsStatus;

You have not, in any code that you've shown, set this pointer to point anywhere. (Are you using an SDK for some robotics package that will initialize this variable for you? If so, can you show the configuration setting that tells it that this is the variable to initialize?)

string_to_send[7] = robotMotorsStatus[0];
string_to_send[8] = robotMotorsStatus[1];

If that robotMotorsStatus has not been initialized by an SDK or by code not shown, then these are accessing memory at a random address. It would not surprise me if this were crashing you, and if this were the “exception” you referred to but did not name.

robotMotorsStatus[0]='1';

Same potential problem here.

NSLog (@"Robot status %s", robotMotorsStatus);

This assumes that robotMotorsStatus contains at least one character, and that the last one is a zero byte (the null character)—i.e., that robotMotorsStatus points to a C string. As I've already noted, you have not shown that robotMotorsStatus points to anything definite, and even if it does point somewhere, you have not shown that the contents of that memory are a C string.

If there isn't a null character within the actual bounds of the array, then the array does not contain a C string, and attempting to read the whole C string, as passing the array to a %s formatter does, will cause a crash after you go past the end of the array. If the other two accesses of robotMotorsStatus are not your crash, this one may be.

The solution here is to not only have the pointer variable point somewhere you've intended, but to have a valid C string—including the null character—completely within that space.

Incidentally, these problems have nothing to do with threads.

Peter Hosey