0

I have a queue that is an array of chars, pointed to by a void pointer named data, this holds the correct address of 0x00008E80.

The tail of the queue is tracked by a simple index integer, in this case it is equal to 6, i.e. the 7th array position.

I'd like to return a pointer to the tail array position, which should be 0x00008E86.

I've tried the following (and some variations thereof) with no luck:

struct queue_t {
    void * data;
    uint16_t tail;
};
char sqData[SQ_LENGTH] = {0};
struct queue_t sq = {0};

void initQueue (queue_t * q, void * d) {
    q->data = d;
}

char * getTailPositionAddress (context_t sc) {
    char * s = (char *)sc->slave->queue->data;
    return (s + sc->slave->queue->tail);
}

void main (void) {
    initQueue(&sq, sqData);
    foo_context->slave->queue = &sq;
    // queue is of type struct queue_t *

    // Do some stuff that pushes data to the queue and then pops a bit of it
    //  so the tail is moved up to the 7th array position
    char * bar = getTailPositionAddress(fooContext);
    // Here bar is always equal to some stupid low address like 0x5 or 0x2!?!
}

Why isn't this working? What would be the correct way to achieve what is intended? Thanks!

13
  • What do you mean when you say this doesn't work ? Can you be more specific ? Did you try stepping through the code in your debugger to see what's going on ? Commented Sep 23, 2014 at 9:49
  • return sc->slave->queue->tail; ? Commented Sep 23, 2014 at 9:52
  • if tail is an integer of some sort then your code is fine and 0x5 or 0x2 are the values pointed by the bar pointer. Commented Sep 23, 2014 at 9:54
  • Show the definitions. Commented Sep 23, 2014 at 10:04
  • 1
    if the optimizations are on it means nothing. The compiler is free to delay writing the value to memory or elide it altogether. You should either output the variable to a file or declare it volatile if you want to examine it. Commented Sep 23, 2014 at 10:21

1 Answer 1

1

The posted program doesn't allow to see what value bar gets in the end, even with a debugger. The compiler is free to rearrange memory writes such that the value is stored in memory long after it's calculated. The compiler can even elide storing it altogether, especially when optimizations are in use.

In order to be able to examine the value of bar, it should be either declared volatile or sent to a file. Declaring it volatile guarantees the value will be stored in memory eventually --- not necessarily right after it's computed, but before any other observable event takes place.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.