1

why do i always get garbage values? I have a problem about garbage values. I wrote this code but i have no idea why it always returns garbage values. Is that because of passing and returning array values? Or is there some other issues? this is c++ code . . . . . . . . . . .

#include<iostream>
#include<queue>
#include<vector>
#define MAX 1000
using namespace std;

int* topologicalSort(int*time, int*indegree, vector<int>*g, int n)
{
    queue<int>q;
    int result[MAX + 1];
    memset(result, sizeof(result), 0);
    for (int i = 1; i <= n; i++)
    {
        if (indegree[i] == 0) {
            q.push(i);
            result[i] = time[i];
        }
    }
    while (!q.empty())
    {
        int x = q.front();
        q.pop();
        for (int i = 0; i < g[x].size(); i++)
        {
            int y = g[x][i];
            indegree[y]--;
            result[y] = max(result[y], result[x] + time[y]);
            if (indegree[y] == 0)
                q.push(y);
        }
    }
    return result;
}
int main()
{
    ios::sync_with_stdio(false);
    cin.tie(NULL);
    cout.tie(NULL);
    int t;
    cin >> t;
    while (t-- > 0)
    {
        vector<int>g[MAX + 1];
        int n;
        int time[MAX + 1];
        int indegree[MAX + 1];      
        int k;
        int dest;
        memset(time, sizeof(time), 0);
        memset(indegree, sizeof(indegree), 0);
        cin >> n >> k;
        for (int i = 1; i <= n; i++)
        {
            cin >> time[i];
        }
        for (int i = 0; i < k; i++)
        {
            int u, v;
            cin >> u >> v;
            g[u].push_back(v);
            indegree[v]++;
        }

        cin >> dest;
        int *r = topologicalSort(time, indegree, g, n);
        cout << r[dest] << '\n';
    }


}

.... .... .... .... .... ....

uma
  • 31
  • 1
  • 2
    I get [a pile of warnings](https://wandbox.org/permlink/Opgssp6NZsPAWgY3) when compiling your code. – Quentin Oct 07 '19 at 10:36
  • 3
    You return the address of a local, non-static variable: `return result;`. -> Bad idea. This is [Undefined Behavior](https://stackoverflow.com/a/4105123/1505939). Local variables are released when their scope is left. Hence, the address to it becomes dangling. The memory might (or might not) be re-used for something else. Hence, reading might return garbage (or even crash), writing might destroy anything or crash, or the destroyed thing might cause a crash later or it might destroy something else or... – Scheff's Cat Oct 07 '19 at 10:36
  • 3
    `return result;` You seem to think `int result[MAX+1]` still exists after returning from that function. You're returning a dangling pointer. Crank up your warnings, treat them *all* as errors (ex: your memset arguments are wrong) and use (and return) a `std::vector` rather than `int*` for that function to convey data back to the caller. – WhozCraig Oct 07 '19 at 10:37

0 Answers0