C++中 指针赋值后 exe程序无法运行
怪我咯
怪我咯 2017-04-17 12:06:38
0
2
705

我在Win8中 使用codeblock编写了一段程序。使用的是GCC 4.7 & 4.8 编译器:

#include <iostream>

using namespace std;

int main()
{
    int *i=0;


    cout<< "Hello world!" << endl;
    return 0;
}

程序可以运行,输出:Hello world。很奇怪的是一旦加入指针赋值语句,编译组建通过,但无法运行。

int main()
{
    int *i=0;
    *i = 9;

    cout<< "Hello world!" << endl;
    return 0;
}


控制台上显示为:
Process returned -1073741819 (0xC0000005) execution time : 1.453 s
使用VC++ 6.0 出现了同样的现象

在百度上也没搜到结果。

怪我咯
怪我咯

走同样的路,发现不同的人生

reply all(2)
大家讲道理
int *i = 0;

This statement is equivalent to assigning the pointer variable i of int* to 0, instead of pointing the pointer i of int* to the memory address where the constant 0 is located, which is equivalent to the following code:

int *i;
i=0;

instead of

int *i;
*i= 0;    //不过这样的用法也不规范!这句代码的作用是为指针 i所指向的内存赋值,
          //但是因为i 指向未知内存,因为前面只是进行了初始化,所以这时候是一个野指针
          //为野指针指向的内存赋值,显然会导致内存错误!

Is this what you understand? @changqngd

阿神

I just ran it a few times and thought about it, and finally figured it out.
The error is:
int *i=0; //这里给指针赋了一个空地址 *i = 9; //*i is a null address pointer and cannot be used
It is correct to change it to the following:

int ival=90;
int *i = &ival;
*i=9;
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template