tags:

views:

62

answers:

1

I've this simple method to shift element in an array.

void queuePut(uint32_t val, uint32_t *q, int qlen) {
    for (int i=qlen; i>0; i--) {
        q[i] = q[i-1];
    }
    q[0] = val;
}

In my class header i defined a struct

@interface MyClass : NSObject {
    struct {
        uint32_t cookie[10];
        uint32_t value[10];
    } queue;
}

I repeatedly put elements in front of both queues

queuePut((uint32_t)cookie, myClassInstance->queue.cookie, cookieQueueLen);
queuePut((uint32_t)intValue, myClassInstance->queue.value, valueQueueLen);

When i do this my value queue layout is as follows over time:

0.0.0.0.0.0.0.0.0.0.
0.0.0.0.0.0.0.0.0.0.
0.0.0.0.0.0.0.0.0.0.
1.0.0.0.0.0.0.0.0.0.
1.0.0.0.0.0.0.0.0.0.
0.0.0.0.0.0.0.0.0.0.
0.0.0.0.0.0.0.0.0.0.
0.0.0.0.0.0.0.0.0.0.
0.0.0.0.0.0.0.0.0.0.
0.0.0.0.0.0.0.0.0.0.

When i remove the first line queuePut((uint32_t)cookie, ... the value queue shows this (what i want it to be):

0.0.0.0.0.0.0.0.0.0.
0.0.0.0.0.0.0.0.0.0.
0.0.0.0.0.0.0.0.0.0.
1.0.0.0.0.0.0.0.0.0.
1.1.0.0.0.0.0.0.0.0.
0.1.1.0.0.0.0.0.0.0.
0.0.1.1.0.0.0.0.0.0.
0.0.0.1.1.0.0.0.0.0.
0.0.0.0.1.1.0.0.0.0.
0.0.0.0.0.1.1.0.0.0.

What causes this?

Regards, Erik

+4  A: 

Exactly what are cookieQueueLen and valueQueueLen?

This is suspect:

void queuePut(uint32_t val, uint32_t *q, int qlen) {
    for (int i=qlen; i>0; i--) {
       q[i] = q[i-1];
    }
   q[0] = val;
}

If you're passing 10 for qlen, then on the first iteration you're writing to q[10], which is past the bounds of the cookie (or value) arrays. You're clobbering memory.

So in this case, you're writing past the end of the cookie array and into the start of the value array.

jamesdlin
oh my god i can't believe how stupid i am. i was sitting hours and i din't see it! but sometimes you just need another person to point you to the obvious ;)
Erik Aigner