C/C++中"安全"和"不安全"代码有什么区别?
我在文章中读到"C++在导致严重安全漏洞的方面不安全":Rust如何与其他语言进行比较.什么是不安全的代码不安全?
我想知道变量的初始化方式:
#include <stdio.h>
int main( void )
{
int ghosts[3];
for(int i =0 ; i < 3 ; i++)
printf("%d\n",ghosts[i]);
return 0;
}
Run Code Online (Sandbox Code Playgroud)
这给我带来了随机值,例如 -12 2631 131 ..它们来自哪里?
例如,x86-64 Linux 上的 GCC:https ://godbolt.org/z/MooEE3ncc
我有一个猜测来回答我的问题,无论如何它都可能是错误的:
内存的寄存器在“清空”后获得 0 和 1 之间的随机电压,这些值“四舍五入”为 0 或 1,并且这些随机值取决于在某事上?!也许寄存器的制作方式?也许内存的容量会以某种方式发挥作用?甚至可能是温度?!!
传递未初始化的变量srand而不是结果是不错的主意time(NULL)?
它是一个#include和一个函数调用较少.
示例代码:
#include <stdlib.h>
int main(void) {
{
usigned seed; //uninitialized
srand(seed);
}
//other code
return 0;
}
Run Code Online (Sandbox Code Playgroud)
代替
#include <stdlib.h>
#include <time.h>
int main(void) {
srand(time(NULL));
//other code
return 0;
}
Run Code Online (Sandbox Code Playgroud) #include <string>
struct T1 { int mem; };
struct T2
{
int mem;
T2() { } // "mem" is not in the initializer list
};
int n; // static non-class, a two-phase initialization is done:
// 1) zero initialization initializes n to zero
// 2) default initialization does nothing, leaving n being zero
int main()
{
int n; // non-class, the value is indeterminate
std::string s; // class, calls default ctor, the value is "" (empty string)
std::string a[2]; // …Run Code Online (Sandbox Code Playgroud) 例如:
int main()
{
int p;
::std::cout << ::std::uintptr_t(&p) << ::std::endl;
}
Run Code Online (Sandbox Code Playgroud)
如果重复执行,这将始终产生“随机”数字。可以在 C 中完成类似的事情。我看不到任何关于它的 UB。
例如,在以下代码中:
int myarray[3];
int x = myarray[1];
Run Code Online (Sandbox Code Playgroud)
代码是否保证在恒定时间内成功执行,x具有一些整数值?或者编译器是否可以跳过为这个完全/发出代码发出代码来启动GNU Chess并仍然符合C++标准?
这在类似于数组的数据结构中很有用,但可以在恒定时间内初始化.(对不起,我没有Aho,Hopcroft和Ullman的副本,所以不能查找名字.)