Leonly91
Leonly91

Reputation: 613

Why pass float parameter to [UIColor getRed:green:blue:alpha] will cause crash:"EXC_BAD_ACCESS"?

Code Sample(iOS 8 Simulator & Xcode6):

-(void)viewDidLoad{
    [super viewDidLoad];

    UIColor *color = [UIColor whiteColor];
    float a,b,c;
    [color getRed:&a green:&b blue:&c alpha:nil];//Incompatible pointer types sending 'float *' to parameter of type 'CGFloat *' (aka 'double *')
}

I know that CGFloat is defined as double on 64 bit devices, but how could this cause crash?

Upvotes: 0

Views: 91

Answers (2)

gnasher729
gnasher729

Reputation: 52538

You are invoking undefined behaviour. Anything can happen, including a crash. Or a crash that will never happen on your machine, but every time Apple reviews your app. Or every time paying customers use your app.

You better check what warnings you have turned off that allow the compiler to compile this code, and turn them back on or turn them into errors.

Upvotes: 0

Joride
Joride

Reputation: 3763

The UIColor method will try to write a double to the memory pointed to by the parameters. This memory is declared as float instead of CGFloat (i.e. double). Not sure about the size of a a float on 64 bit machines, but my guess is that a float is smaller than double. So that method (getRed:green:blue:alpha) is writing into memory that is not owned by you (or the app, hence the bad access.

Also, as this method is expecting pointers (a C-concept), you should not pass nil, but NULL. Although they are both identical from a compiler's perspective, your intent and understanding is more clear when you are passing the correct type.

Upvotes: 2

Related Questions