-2

I'm working on using pointers to add objects to a queue and ran into a weird behavioral problem I can't quite figure out.

Each object that gets added to the queue has a 'next' pointer that links them all together and I have a 'start' and 'end' pointer to keep track where each end of the queue is.

The problem I have is that when I pass the end pointer and the object (which is stored in pArray by its processID), it also changes the start pointer -- even though I'm not passing it to the function.

// snippet from my main.cpp
RQCount = 0;
if (RQCount == 0)
    {
        RQStart = &pArray[processID];
        RQStart -> next = &pArray[processID];
        endRQ = &pArray[processID];
        pArray[processID].setStatus("Ready");

        CPUHolder = RQStart;
        CPU = RQStart -> CPUBurst;

        RQStart ->pStatus = "Executing";
    }
    else
    {
        *endRQ = FCFS(endRQ, &pArray[processID]);
        pArray[processID].setStatus("Ready")
    }
RQCount++;

FCSC Method:

PCB FCFS (PCB *endRQ, PCB *obj)
{
    endRQ -> next = obj;
    endRQ = obj;

    return *endRQ;
};

I've narrowed it down to the function, and what really stumps me is that I move those two lines of code to my main, it runs and behaves just fine. It's when I add the function it doesn't. I think it has to do with how I'm dealing with the pointers and dereferencing, but I could use some help understanding this. Thanks!

EDIT:

To emphasize, I'm not having an issue with variables not changing in the function, as someone marked this a duplicate question for. The issue is after the function is called, it changes RQStart (which is not passed to the function).

If I don't use a function, RQStart stay the same, when I use the function, RQStart changes to a different object.

miliardo18
  • 25
  • 6
  • 1
    Weird behavioral problem is what I see a lot on stack overflow. – SergeyA Feb 16 '16 at 20:17
  • `return *endRQ;` returns a copy of `endRQ`, that's probably not what you want. – πάντα ῥεῖ Feb 16 '16 at 20:18
  • You need to post a [**Minimal Complete** Verifiable Example](http://stackoverflow.com/help/mcve). Actually, in the process of developing an MCVE, I expect that you'll find the problem yourself. – user3386109 Feb 16 '16 at 20:37
  • _**"If I don't use a function, RQStart stay the same, when I use the function, RQStart changes to a different object."**_ Well, that's a strong sign you are hitting undefined behavior in your code. Unless you are posting a [MCVE] we actually can't tell what the problem is. – πάντα ῥεῖ Feb 16 '16 at 20:37

1 Answers1

0

If you do

    RQStart = &pArray[processID];
    // ...
    endRQ = &pArray[processID];

and then pass endRQ to the function, that will be the same as if you passed RQStart.

So when you change endRQ->next that will also change RQStart->next.

This is one reason for the standard containers to have end() point one past the last element, and not to the last element.

Bo Persson
  • 90,663
  • 31
  • 146
  • 203