Why do I get EXC_BAD_ACCESS even though the pointer appears to be valid?

Tuesday, July 1, 2014

I start with an integer array test[] which represents a set of images. The first two elements of test[] are the height and width of the first image. The following four (height*width) elements are pixel values. The next six represent the next image and so on.


My goal is to access the images through image objects without duplicating anything in the test[] array. I try to do this via ImageSet::import.



int main(){
int test[] = {2,2,1,2,3,4,
2,2,4,5,6,7,
2,2,9,8,0,9};
ImageSet set = ImageSet();
set.import(test); //ImageSet::import
return 0;
}


ImageSet::import uses the cursor variable to store the start index of the next image. it calls Image::import to read that data into an image object. The data for that particular image should start at the address &data[cursor].



void ImageSet::import(int data[]){
int cursor = 0;
for(int i = 0; i < NUM_SRC_IMAGES; i++){
int height = data[cursor];
int width = data[cursor+1];
source_[i].import(&data[cursor]); //this is Image::import
cursor += height * width + 2;
}
}


Within image::import, I get a bad access by attempting to read data[0]. According to the debugger, data[] points to the correct value of 2, but EXC_BAD_ACCESS is thrown anyway when I attempt to get that value via data[0].



void Image::import(int data[]){
height_ = data[0]; //the problem occurs right here
width_ = data[1];
matrix_ = &data[2];
}


I would very much appreciate an explaination of what I am doing wrong. I would equally appreciate suggestions for how to achive my goal without pointer arithmetic.


Thank You!







http://ift.tt/1iTuFfo