指针地址的越界,编译器难以发现错误
代码如下:
#include
using namespace std;
int main()
{
int a;
int num = 0;
int * p = #
// 右移越界
p[-1] = 2; //out of bound
p[0] = 3; //okay
// 左移越界
*(p+1) = 4; //out of bound
// 根据指针地址对元素数值进行修改
cout << "num = " << num << endl;
return 0;
}
数组索引的越界,编译器也不易发现错误
代码如下:
#include
using namespace std;
int main()
{
int num_array[5];
// 内存是连续的,数组溢出产生的错误可能很难发现
// -1是下溢的数组
for(int idx = -1; idx <= 5; idx++) //out of bounds
num_array[idx] = idx * idx;
for(int idx = -1; idx <= 5; idx++) //out of bounds
cout << "num_array[" << idx << "] = " << num_array[idx] << endl;
return 0;
}
// num_array[-1] = -1
// num_array[0] = 0
// num_array[1] = 1
// num_array[2] = 4
// num_array[3] = 9
// num_array[4] = 16
// num_array[5] = 25
代码如下(示例):
#include
using namespace std;
struct Student
{
char name[4];
int born;
bool male;
};
int main()
{
// c++申请一个堆内存
//allocate an int, default initializer (do nothing)
int * p1 = new int;
//allocate an int, initialized to 0
int * p2 = new int();
//allocate an int, initialized to 5
int * p3 = new int(5);
//allocate an int, initialized to 0
int * p4 = new int{};//C++11
//allocate an int, initialized to 5
int * p5 = new int {5};//C++11
//allocate a Student object, default initializer
Student * ps1 = new Student;
//allocate a Student object, initialize the members
// g++ newdelete.cpp -std=c++11// c++11以及更高版本的标准才能使用{}进行初始化
Student * ps2 = new Student {"Yu", 2020, 1}; //C++11
// Student * ps2 = new Student "Yu", 2020, 1; //C++11
//allocate 16 int, default initializer (do nothing)
int * pa1 = new int[16];
//allocate 16 int, zero initialized
int * pa2 = new int[16]();
//allocate 16 int, zero initialized
int * pa3 = new int[16]{}; //C++11
//allocate 16 int, the first 3 element are initialized to 1,2,3, the rest 0
int * pa4 = new int[16]{1,2,3}; //C++11
//allocate memory for 16 Student objects, default initializer
Student * psa1 = new Student[16];
//allocate memory for 16 Student objects, the first two are explicitly initialized
Student * psa2 = new Student[16]{{"Li", 2000,1}, {"Yu", 2001,1}}; //C++11
cout << psa2[1].name << endl;
cout << psa2[1].born << endl;
//deallocate memory
delete p1;
//deallocate memory
delete ps1;
//deallocate the memory of the array
delete pa1;
//deallocate the memory of the array
delete []pa2;
//deallocate the memory of the array, and call the destructor of the first element
delete psa1;
//deallocate the memory of the array, and call the destructors of all the elements
delete []psa2;
return 0;
}