函数内使用指针

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


(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
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值