我在运行期间遇到了这个非常奇怪的错误。
我的程序有两个参数,用它们做一些数学计算,最后是std::cout
的值。
如果我输入一些值,我的程序可以工作,但是如果我输入其他值,它表示正在使用一个变量而没有被初始化,我认为它没有任何意义。
以下是代码:
#include <iostream>
#include <stdio.h>
#include <cmath>
double align_nb(int n) { return { ceil(n / 512.0)*512.0 }; } // bytes
double align_pt(int k) { return { floor(k / 512.0)*512.0 }; } // pointer
int main(int argc, char * argv[])
{
int o_n = std::atoi(argv[1]); // original number
int o_p = std::atoi(argv[2]); // original pointer
int max_bytes, new_pointer; // max bytes to read, new pointer to point
float log = (std::log(o_n) / std::log(2));
if (log != floor(log))
{
max_bytes = align_nb(o_n); // bytes alinhados para a frente
new_pointer = align_pt(o_p); // ponteiro alinhado atrás
}
else if (log == floor(log))
{
new_pointer = align_pt(o_p);
if (max_bytes + (o_p - new_pointer) >max_bytes)
{
max_bytes += 512;
}
}
std::cout << "Original bytes= " << o_n << std::endl;
std::cout << "Original pointer= " << o_p << std::endl;
std::cout << "Max_bytes= " << max_bytes << std::endl;
std::cout << "new_pointer= " << new_pointer << std::endl;
return 0;
}
以下是我测试它的值并且它崩溃了,给了我运行时错误:
2048 513
1024 500
这里有一个值的例子,代码没有给我那个错误,程序有效:
513 520
Here是它给我的错误的印刷品。
我真的很感激有人在解释我为什么会给我这个错误/如何修复它。 无论如何,谢谢!
(PS:包含数学标记,因为它可能是程序中的数学导致它崩溃。如果annyone认为它在这个问题中使用,请在评论中告诉我并删除它。)< / p>
(PS 2:当它给我运行时错误时它抱怨的变量是'max_bytes'。)
答案 0 :(得分:-1)
如果您的代码在第17行采用了else路径,那么您的代码不会初始化max_bytes
,但会在之后使用它。这就是问题所在。
注意:
答案 1 :(得分:-1)
确保对于代码采用的每个路径,初始化您使用的变量的值。如果不这样,您将获得所谓的未定义行为。未初始化的变量中可能存在任何内容。
int max_bytes;
....
....
expression_involving_max_byte <- Dangerous!