gpt4 book ai didi

c++ - 同一程序多次执行的未定义行为

转载 作者:行者123 更新时间:2023-11-28 03:44:37 24 4
gpt4 key购买 nike

当我在 VS2010 中的 Release 中编译相同的程序时,我得到了一个奇怪的行为。如果我多次从 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();
}

其余代码只是 setter/getter 。现在对于我作为输入给出的文件:

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

最佳答案

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

memset(R, 0, capacity + 1);

应该是:

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

由于您没有将所有 R 置零,因此它的上半部分未定义并且给您垃圾数据。

关于c++ - 同一程序多次执行的未定义行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8003902/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com