2011-11-04 23 views
0

当我在VS2010中编译相同的程序时,出现一个奇怪的行为。如果我多次从cmd.exe运行该程序,结果会变得无法理解。但是,如果我在Debug中运行程序,结果总是相同的。在同一程序的多次执行中未定义的行为

启动新的命令提示符会使程序再次发出正确的输出。

有什么想法可能会导致这种情况?

Screenshot of the command prompt

编辑:代码:

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(); 
} 

的代码的其余部分是唯一的干将。现在我输入文件:

 
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 
+0

显然,一些未定义的行为。代码需要做任何有意义的诊断。它可能是*任何东西*读取或写入到您不应该以这种方式使用的内存位置,或者导致此类内存访问在其他地方完成的其他一些内容,或完全是其他内容。 – delnan

+0

会发布代码,但是我惊讶于只发生在第二次执行程序 –

回答

2

您的memset是不正确的。你忘了sizeof()

memset(R, 0, capacity + 1); 

应该是:

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

既然你没有零所有的R,它的上部分是不确定的,是给你的垃圾数据。

+0

该死的时候。有一段时间没有完成C++,现在它显示。非常感谢! –