PiotrDomo
PiotrDomo

Reputation: 1045

Strange behaviour on C array

I found really strange behaviour when looping through NSString array. The thing is it happens only in iOS 32bit environment, but on 64bit works as expected.

here is the code I run:

static NSString * const HexColors[3] = {
    @"FFFFFF",
    @"FF0000",
    @"000000"};

static NSString * const ColorDescription[3] = {
    @"white",
    @"red",
    @"black"};

in implementation file I loop as following

- (void)loop {
    NSInteger i = 0;
    while (HexColors[i]) {
        NSLog(@"%@", HexColors[i]);
        i++;
    }
}

The result I get:

2014-04-25 09:57:45.374 loopApp[587:60b] FFFFFF
2014-04-25 09:57:45.375 loopApp[587:60b] FF0000
2014-04-25 09:57:45.376 loopApp[587:60b] 000000
2014-04-25 09:57:45.376 loopApp[587:60b] white
2014-04-25 09:57:45.377 loopApp[587:60b] red
2014-04-25 09:57:45.377 loopApp[587:60b] black

And then app throws EXC_BAD_ACCESS on NSLog line

I could use "for" loop but this is not the case

Any idea why it happen? Is it the clang issue?

Upvotes: 0

Views: 56

Answers (2)

paxdiablo
paxdiablo

Reputation: 882606

The line:

while (HexColors[i]) ...

will only stop at the end of the array if there's some NULL marker there, so you have a couple of options (at least).

First, you can put a NULL marker there, with:

static NSString * const HexColors[] = {
    @"FFFFFF",
    @"FF0000",
    @"000000",
    NULL};

Note also there the indeterminate array size [] which creates an array based on the data itself. That's often preferred when you supply all the data and don't want to change too much when you add items.

Second (without adding the NULL element), you can limit your loop using a better test:

for (i = 0; i < sizeof (HexColors) / sizeof (*HexColors); i++) ...

That expression sizeof (HexColors) / sizeof (*HexColors) gives you the number of array elements in HexColors.


As an aside, the reason you're seeing both arrays output is because of how they're laid out in memory. The ColorDescription array immediately follows HexColors so it's as if that's just one array according to your slightly awry loop.

Then, following ColorDescription is a pointer (or arbitrary value interpreted as a pointer) that causes the memory fault.

                 +---------+
HexColors        | pointer | --> "FFFFFF" (all nul-terminated
                 | pointer | --> "FF0000"  character arrays)
                 | pointer | --> "000000"
                 +---------+
ColorDescription | pointer | --> "white"  (ditto)
                 | pointer | --> "red"
                 | pointer | --> "black"
                 +---------+
ArbitraryMemory  | ??????? | --> ???????  (except here, which
                 +---------+               could be anything)

Upvotes: 2

Parag Bafna
Parag Bafna

Reputation: 22930

Change your while (HexColors[i]) condition.

 while (i < arrayCount)

to avoid index 3 beyond bounds.

Upvotes: 1

Related Questions