views:

148

answers:

2

I am trying to modify pixel values (8 bits per channel RGBA) by numerically increasing/decreasing the values by a certain amount. How can I do this in Objective-C or C? The following code generates a "Error: EXC_BAD_ACCESS" everytime.

// Try to Increase RED by 50
    for(int i = 0; i < myLength; i += 4) {

     //NSLog prints the values FINE as integers
            NSLog(@"(%i/%i/%i)", rawData[i], rawData[i+1], rawData[i+2]);

            //But for some reason I cannot do this
     rawData[i]+=50;

}

and even

// Try to set RED to 50
    for(int i = 0; i < myLength; i += 4) {

            //I cannot even do this...
     unsigned char newVal = 50;
     rawData[i] = 50;

}

Sidenote: rawData is a data buffer of type unsigned char

A: 

Hmm... What's rawdata? Maybe it's a const type which you can not modify?

MaxVT
rawData is of type unsigned char. unsigned char As in: *rawData = malloc(height * width * 4);
RexOnRoids
+4  A: 

It's possible that you're overrunning the end of your allocated buffer, and that's why you're getting the access violation. That most likely means that your math is wrong in the allocation, or your rawData pointer is of the wrong type.

If you are accessing the raw data of a loaded UIImage, it might be mapped into memory read-only. You'd need to copy the data into a buffer that you allocated, most likely.

Mark Bessey
Yes, I was overrunning the end of the buffer -- Thanks! BTW, do you know of any good way to test for the end of the buffer if the buffer rawData is defined as *rawData = malloc(height * width * 4);?
RexOnRoids
I don't think there is a good test other than keeping track of where you are writing. Isn't myLength = height * width * 4. BTW, there may be some extra padding bytes at the end of each row, to align it to certain byte boundaries. If you have a rowBytes value, use it in conjunction with width to know when you hit the padding.
mahboudz
It's possible to detect buffer overwrites at run-time if you suspect they're happening. "man malloc" in a Terminal window will give more information on the debugging facilities available. On the other hand, EXC_BAD_ACCESS is a strong indicator of a buffer overrun, in any case.
Mark Bessey