Med*_*her 1 c++ arrays integer overflow
示例代码:
#include <stdio.h>
class compArray {
public:
unsigned int* myArr; //The array
compArray() {
unsigned int temp[4];
for (unsigned int i=0;i<4;i++) {
temp[i] = 0;
}
myArr = temp;
print_arr(myArr);
}
void set() {
print_arr(myArr);
}
static void print_arr(unsigned int* arr) {
printf("Printing the array============\n");
for (unsigned int i=0;i<4;i++) {
printf("%u\n",arr[i]);
}
printf("\n");
}
};
main() {
compArray test;
test.set();
}
Run Code Online (Sandbox Code Playgroud)
输出:
打印数组============
0
0
0
0打印阵列============
134513919
3221174380
0
0
我确信这很简单,我很想念,但为什么会这样呢?
在构造函数中,您有以下两行:
unsigned int temp[4];
...
myArr = temp;
Run Code Online (Sandbox Code Playgroud)
您将成员变量指针设置为myArr等于本地变量的地址temp.但是,temp超出范围,一旦从构造函数返回就会被销毁.
之后,myArr指的是不再分配的存储,并显示未定义的行为.
| 归档时间: |
|
| 查看次数: |
110 次 |
| 最近记录: |