简体   繁体   中英

Undefined behavior on multiple execution of the same program

I get a strange behavior when I compile the same program in Release in VS2010. If I run the program from cmd.exe multiple times, the results become gibberish. However, if I run the program in Debug, the result is always the same.

Starting a new command prompt makes the program give out the right outputs again.

Any idea of what might be causing this?

命令提示符的屏幕截图

Edit : The code :

int main(int argc, char* argv[])
{
    int* R;
    int capacity;

    if (argc < 2)
    {
        cerr << "Veuillez entrer le chemin du fichier d'entree" << endl;
        return 1;
    }

    vector<BTS> stations;
    LoadFromFile(argv[1], stations, capacity);

    int count = 1;
    if (argc == 3)
    {
        count = atoi(argv[2]);
    }

    clock_t startClock = clock();

    R = new int[capacity+1];
    for(int j = 0; j < count; j++)
    {
        memset(R, 0, capacity + 1);

        for(unsigned int i=0; i < stations.size(); i++)
        {
            for(int j=capacity; j >= 0; j--)
            {
                if(j-stations[i].getNumberOfSubscribers() >= 0)
                {
                    R[j] = max(stations[i].getRevenue() + R[j-stations[i].getNumberOfSubscribers()], R[j]);
                }
            }
        }
    }

    // Print the results
    cout << "Value : " << R[capacity] << endl;
    cout << "Temps total : " << ((float)(clock() - startClock) / (float)CLOCKS_PER_SEC) << " s" << endl;

    delete[] R;

    return 0;
}

void LoadFromFile(std::string filePath, std::vector<BTS>& baseStations, int& capacity)
{
    fstream source(filePath);

    int numberOfStation;
    source >> numberOfStation;
    source >> capacity;

    for (int i = 0; i < numberOfStation; i++)
    {
        int index, revenue, numberOfSuscribers;
        source >> index;
        source >> revenue;
        source >> numberOfSuscribers;

        BTS station = BTS(index, revenue, numberOfSuscribers);

        baseStations.push_back(station);
    }

    source.close();
}

The rest of the code is only getters. Now for the file I give as input :

10 25
    1     7     6
    2     4     4
    3     7     6
    4     2     1
    5     7     8
    6     9    10
    7     4     5
    8    10    10
    9     1     1
   10    10    10

Your memset isn't correct. You forgot the sizeof() :

memset(R, 0, capacity + 1);

should be:

memset(R, 0, (capacity + 1) * sizeof(int));

Since you didn't zero all of R , the upper parts of it are undefined and are giving you junk data.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM