Memory Access Problem

Can you help me resolve this question, please? I do appreciate it. float *h is an instance variable, x = 2, when I call this function, in gdb it shows that


Program received signal EXC_BAD_ACCESS, Could not access memory.
Reason: KERN_INVALID_ADDRESS at address: 0x000000000100a370
0x0000000100001e2d in ImageGS::hist (this=0x100100a41, x=2) at ImageGS.cpp:180
180				h[i] = float(array[i])/num;


before the (array[loc])++;[this is highlighted in codes with "//////"], everything is right, r =375, c=500. But after this array evaluation loop, h cannot be got using "print h[0]", which is "Cannot access memory at address 0x100a370"

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
float *ImageGS::hist(int x){  // this is a function to calculate histogram
	int array[L_LUM];
	int num = r*c;
	float *w = new float[L_LUM];
	if(h_flag == 0){

		if(w == NULL){
			cout<<"hist dynamic allocation faiiled"<<endl;
			exit(1);
		}
		h = w;
	}
	else if(h_flag == 1){
		return h;
	}
	cout<<r<<" "<<c<<" "<<h[1]<<endl;
	int loc =0;
	//float count =0;
	for(int i=0; i<L_LUM; i++){			//initialize
		array[i] = 0;
	}
///////////////////////////////////////////////////////////////
//PROMBLEM HAPPENS
	for(int i=0; i<r; i++){				//count
		for(int j=0; j<c; j++){
			loc = image[i][j];
			//cout<<image[i][j]<<endl;
			(array[loc])++;
		}
	}
//////////////////////////////////////////////////////
	cout<<loc<<endl;

	cout<<"the histogram is:";
	if(x == 1){
		cout<<"(percentage)"<<endl;
		for(int i=0; i<L_LUM; i++){			// transform to pdf, percentage x =1
			h[i] = float(array[i]*100)/num;
			cout.width(5);
			cout.precision(3);
			cout<<h[i];
			if(i%10==0){
				cout<<endl;
			}

		}
	}
	else{
		cout<<"(nonpercentage)"<<endl;
		for(int i=0; i<L_LUM; i++){			// transform to pdf, not percentage x=2
			h[i] = float(array[i])/num;
			cout.width(5);
			cout.precision(3);
			cout<<h[i];
			//cout.width(8);
			//cout<<array[i];
			if(i%10==0){
				cout<<endl;
			}
			//count= count+ h[i];
		}
	}
	cout<<endl;
	//cout<<count<<endl;

	h_flag = 1;
	return h;
}
Last edited on
loc is probably out of range.

make sure it's within the bounds of your array. (ie: >= 0 and < L_LUM)
Thank you!
Topic archived. No new replies allowed.