We have an NSMutableData object that frequently has data appended to it. We also frequently pull out data via the bytes method for reading.
We’ve synchronized access to this NSMutableData object via a pthread mutex:
pthread_mutex_t _mutex;
pthread_mutexattr_t attributes;
pthread_mutexattr_settype( &attributes, PTHREAD_MUTEX_DEFAULT );
pthread_mutex_init( &_mutex, &attributes );
and then every time we access this object we:
pthread_mutex_lock(&_mutex);
const UInt8* rawData = [_coverage bytes];
//code that works with the raw bytes
pthread_mutex_unlock(&_mutex);
Also, every addData method we have locks the mutex before adding data to the NSMutableData object.
The problem is we still get the occasional EXC_BAD_ACCESS while working with rawData. I understand that NSMutableBytes will grow its byte array as data gets added to it. I also understand that I shouldn’t expect rawData to magically grow also.
I’m just wondering how we can ever get into this situation where rawData has been free’d from underneath us when we have explicitly locked access for both read and write?
Are we doing something wrong with the mutex or the way we are accessing the bytes?
EDIT
I discovered the real reason why I was getting an EXC_BAD_ACCESS. I was not initializing the mutex attributes, so locking the mutex did nothing. Here is the corrected code:
pthread_mutex_t _mutex;
pthread_mutexattr_t attributes;
pthread_mutexattr_init(&attributes);
pthread_mutex_init(&_mutex, &attributes);
pthread_mutexattr_destroy(&attributes);
Yes it is possible that is being freed from underneath you.
According to the documentation:
You should make copies of the data to ensure that it will not be changed or freed from underneath you. When your done with your copy make sure to
free()it.