Search code examples
c#detectioninfinite-loop

Unable to detect any error but my programs hangs


For example i have to matrices

  Allocation Matrix

  0 0 1 0
  2 0 0 1
  0 1 2 0

  Request matrix
  2 0 0 1
  1 0 1 0
  2 1 0 0

  Resources in Existence: 4 2 3 1
  Available resources: 2 1 0 0

My Code

            for (w = 0; w < TRows; )
            {
                if (Finish[w] == 0)
                {
                    flag = 0;
                    for (x = 0; x < TColumns; x++)
                    {
                        if (A[x] >= Request[w, x])
                            flag = flag + 1;
                    }
                    if (flag == TColumns)
                    {
                        T[y] = w;
                        Finish[w] = 1;
                        for (x = 0; x < TRows; x++)
                        {
                            A[x] = A[x] + Allocation[w, x];
                        }
                        y = y + 1;
                        w = -1;
                        //break;
                    }
                    w++;
                }
            }

Solution

  • First of all, use more descriptive variable names. Your code is almost impossible to read. I did spot at least one problem though:

    for (w = 0; w < TRows; )
    {
        if (Finish[w] == 0)
        {
            /* snip */
            w++;
            /* snip */
        }
    }
    

    If Finish[w] (whatever that means) ever ends up being something else than 0. w will never get incremented and you've got yourself an infinite loop. And if it was always 0, you wouldn't need that test to begin with. Something is wrong with your logic here.