函数返回字符指针 [英] functions returning char pointer

查看:121
本文介绍了函数返回字符指针的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我遇到了很多在一个遗留应用程序返回字符指针的函数。
有些把他们送回指向本地字符数组。这似乎是经过多次的调用导致崩溃(不会马上!)请参见下面

使用

 的char * F1(){
  字符的buff [20];
  字符* PTR;  ----
  ----
  PTR = BUFF;
 返回PTR;
}---
---F2(F1());

F1()返回一个指向局部变量,然后把它传递给另一个函数。我直接拿到了崩溃时,它在MS DEV使用_DEBUG模式编译。但是在释放模式,它不导致立即死机,但赚很多这样的电话后,就可能发生。

当我修改了用法如下,它的工作没有任何问题。就是下面的用法
安全吗?

 的strcpy(ARR,F​​1()); / * ARR是固定的字符数组* /
F2(ARR);


解决方案

没有,这是不确定的行为。它只是发生在你的情况下工作,但可能随时停止工作。

I came across lot of functions returning char pointers in one legacy application. Some of them returning pointers to local character arrays. It seems to be causing crashes after several invocations(not immediately!) see the usage below

char *f1(){
  char buff[20];
  char *ptr;

  ----
  ----
  ptr=buff;
 return ptr;
}

---
---

f2(f1());

f1() returns a pointer local variable and then passes it to another function. I got the crash directly when it's compiled using _DEBUG mode in MS DEV. But in release mode, it doesnt cause an immediate crash, but it might occur after making lots of such calls.

When I modified the usage as below, it's working without any issues. Is the following usage safe?

strcpy(arr,f1()); /* arr is fixed char array*/
f2(arr);

解决方案

No, it is undefined behaviour. It just happens to work in your case, but may stop working at any time.

这篇关于函数返回字符指针的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆