函数内使用指针

来源:互联网 发布:同性约会软件 编辑:程序博客网 时间:2024/06/06 01:18

内存题,问下列程序会输出什么?(大致是原题,有些是自己的扩展)


(1).
#include <iostream>
using namespace std;

 

void fa(char *p)
{
 p = new char[10];
}

 

int main()
{
 char *p=NULL;

 fa(p);
 strcpy(p, "Hello!");
 printf("%s\n", p);

 return 0;
}

运行时错误,某某指令引用的内存0x00000000不能为written.

执行完fa(p);其实指针p还是NULL,因为动态申请的10bytes在fa()返回就释放掉了。

 

(2)
#include <iostream>
using namespace std;

 

char *fb(void)
{
 char *p;
 p = new char[10];
 
 return p;
}

 

int main()
{
 char *p=NULL;

 p = fb();
 strcpy(p, "World");
 printf("%s\n", p);

 return 0;
}
正常输出“World”(即使World后面还有很多内容,也是正常输出)

 

(3)
#include <iostream>
using namespace std;

 

char *fc(void)
{
 char *p = NULL;
 p = "Brian";
 
 return p;
}

 

int main()
{
 char *p=NULL;

 p = fc();
 printf("%s\n", p);

 return 0;
}
正常输出"Brian"


(4)
#include <iostream>
using namespace std;

 

char *fd(void)
{
 char *p = NULL;
 p = "Brian";
 
 return p;
}

 

int main()
{
 char *p=NULL;

 p = fd();
 strcpy(p, "zhang!");
 printf("%s\n", p);

 return 0;
}
运行时错误,某某指令引用的某某内存不能为written.


(5)
#include <iostream>
using namespace std;

 

char *fe(char **p)
{
 *p = new char[10];// Unhandled exception
 return *p;
}

 

int main()
{
 char **p=NULL, *str;

 str = fe(p);
 strcpy(str, "zhang!");
 printf("%s\n", str);

 return 0;
}

运行时错误,某某指令引用的某某内存不能为written.

从第一行打断点开始调试,走到fe()的第一条语句时回弹出异常,说访问不合法。Unhandled exception in ... Access Violation.


(6)
void ff(void)
{
 char *p = new char[13];

 strcpy(p, "Hello world!");
 free(p);
 if(NULL != p)
 {
  printf("%s\n", p);
 }
}
输出乱码!“葺葺葺葺葺葺葺葺葺葺葺葺葺葺葺葺?”

0 0
原创粉丝点击