Object is set to NULL after returning from a member function

Hi guys,
My program seems to crash in the weirdest state. While debugging with gdb, I found that just after return from member function the whole object is set to NULL. The member function executes correctly with correct output but when it returns back to the calling function (another member function), the object itself is NULL (0x0) and program crashes with segmentation fault.

Pseudo code (no C/C++ compilation errors. So ignore obvious compilation errors.)
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
class Employee
{
public:
	BOOL process(){
		
		SomeBigStruct returninfo;    // Step 1

		calculate(returninfo);	     // Step 2
						
		printout(returninfo);        // Step 3

	}
	
	void  calculate(SomeBigStruct& returninfo){
	
		int i=0 ;
		SmallStruct[16] sma;

		..
		..
		..  // Fill up all 16 indexes in sma.
		..
		
		for(i=0;i<16;i++){
			memcpy(&returninfo.returnArray[i], &(sma[i]), sizeof(SmallStruct));     // Step21
		}	

		return;  // Step 22
		
	} // Step 23


	void printout(SomeBigStruct& returninfo){
		
		for(i=0;i<16;i++){
			printf("%d\n", returninfo.returnArray[i].index);
		}	

	}
}


Main(){

	Employee e1;

	e1.process();	

}





So while running in gdb, Step 1 works fine.

Step 21 (all 16 times) works fine.

In Step 21 and 22 and 23, "p this" in gdb gives a valid pointer (with valid information).
In Step 22 and 23, the returninfo object correctly displays all the 16 values
In Step 23, "p *this" gave a integer 183729782880.

At end of Step 2 (before Step 3), returninfo object correctly displays all the 16 values.
At end of Step 2 (before Step 3), "p *this" gives same integer 183729782880.
At end of Step 2 (before Step 3), "p this" is 0x0 and calling printout on 0x0 throws a Segmentation Fault!


One of the winning theory is memcpy is overflowing onto the object itself. it does not look like it but I can spend time in that area digging deeper.

Where could the error possibly be? I need some direction to where to look.
BTW, not sure if it helpful but in gdb after Step 1

sizeof(returninfo) = 5000
sizeof(*this) = 512

You didn't post enough code for us to spot the problem. You'll need to post more.

Although you do have some questionable design decisions....

Why are you doing this:

1
2
3
		for(i=0;i<16;i++){
			memcpy(&returninfo.returnArray[i], &(sma[i]), sizeof(SmallStruct));     // Step21
		}


Instead of this less error prone approach:

1
2
for(i = 0; i<16; ++i)
    returninfo.returnArray[i] = sma[i];


Or even just use std::copy? memcpy is bad news, especially if SmallStruct is a non-POD type.
Topic archived. No new replies allowed.