-1

Could anyone help with this (I guess pointer and memory allocation problem-- At run time the code does not work if I remove the //COMMENTED// cout statement The two *in and *out of struct data structure E although treated in the same manner, only the *in gives me the output as desired

struct V
{
      int al;
      V *next;
};

struct E
{;
      int id;
      V *in;
      V *out;
};

void init(E *edges, int count)
{
    int i = 0;

    int id = 1;
    while (i < count)
    {
        edges[i].id = id;
        edges[i].out = new V;
        edges[i].out->al = 0;
        edges[i].out->next = NULL;
        edges[i].in = new V;
        edges[i].in->al = 0;
        edges[i].in->next = NULL;
        i++; id++;
    }
    i =0;
    while (i < count)
    {
        cout<<"Edges are:"<<endl;
        cout<<"Edge In "<<i<<" is "<<edges[i].in->al<<endl;
        //cout<<"Edge Out "<<i<<" is "<<edges[i].out->al<<endl;
        i++;
    }
}

int main()
{
       int counter=5;
       E *edges = new E[counter];
       init(edges,counter);
}
rishee
  • 1
  • 1
  • 1
    Stop shouting, add proper indentation, and use a code-block instead of a stack-snippet (those are for HTML+CSS+JS)! You can [edit] it. – Deduplicator Nov 12 '14 at 03:49

2 Answers2

1

See this line

edges[i].id = ++i;

You are changing i, but then continue to use it for your later statements. This will leave some of your elements uninitialized and others will try to write outside of your array boundaries.

Edit: As Deduplicator points out, this is undefined behavior (UB) even before it gets to the next statement. You can't rely on which order the left and right hand sides of the assignment operator are evaluated, so (for example) the i++ might happen before the edges[i] part. This question has some informative answers.

Community
  • 1
  • 1
The Dark
  • 8,453
  • 1
  • 16
  • 19
  • How so? If you mean because `i` is changed before it is used in this statement, why not say so? If you mean something else, why not say that? Edit: Ah, I see you added "UB" to your comment, never mind. – The Dark Nov 12 '14 at 03:54
  • The statement is UB even if it is executed with i == 0 and edges is at least 2 elements big. – Deduplicator Nov 12 '14 at 03:56
  • Thanks.. I was able to fix this. – rishee Nov 12 '14 at 04:52
1

This line has a bug: edges[i].id = ++i; Here array element at index 1 is getting assigned instead of intended element at 0 index. Change it to something like: edges[i].id = i+1; and increment i at the end of while loop.

saharsh-jain
  • 486
  • 7
  • 11