while writing native c++ code and i see same programme works fine in xcode(iOS), though crashes in eclipse(android). I could find the problem code and that was due a bad memory access. I wonder why xcode(iOS) didn’t hit the same bad access hence crash.
Actually i created a class say “class_A” which inherits other class say class_B. Later in the code i created the same class instance pointer and assigned the return object of function foo() (belongs to class_B) which returns the object of type super class i.e class_B.
code snippet …
class class_A : public class_B
{
public:
};
class_A *tempPart = (class_A *)class_A::foo("abc.png");
if(tempPart)
{
-------------------
--------------------
}
Now, while accessing _tempPart the programme crashes for android (eclipse), however xcode(iOS) always works fine. I could figure out that as fn foo() returns the object of type class_B hence i was assigning a super class(smaller size object) class_B’s object to inherited class (a bigger size object) Class_A’s object hence it was causing a bad memory access.
But i couldn’t figure out why the same issue is not seen on xcode(iOS).
i am new to xcode and c++, so please help me to understand this.
Undefined behavior is undefined.
Doing things like accessing invalid memory results in undefined behavior in C++. The result may often be a crash, but C++ doesn’t guarantee such things. Instead the program may simply behave oddly, or even exactly as you intended with no indication of an error. Different implementations may do different things.
Here’s some info that may help explain why C++ has undefined behavior (as opposed to languages like Java which work very hard to rule out undefined behavior).
What Every C Programmer Should Know About Undefined Behavior
It’s not entirely clear from your description what’s really going wrong. You say something about assigning a bigger object to a smaller object causing bad memory access, however that’s not the way assignment in C++ works, and the example code is using pointers anyway. The following code is completely legal and well defined, for example:
Where a problem occurs is:
So, assuming this is what your program is doing, the same error in Java is well defined to cause an exception. In Objective-C the message passing machinery will try to find an implementation for the selector at runtime and if it does not find anything then an ‘unrecognized selector’ exception occurs.