返回一个指向静态局部变量安全吗? [英] Is returning a pointer to a static local variable safe?

查看:262
本文介绍了返回一个指向静态局部变量安全吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我与广泛使用指针返回到静态局部变量的成语一些code工作。例如:

  char * const的GetString的()
{
  静态炭STEST [5];
  的strcpy(STEST,测试);
  返回STEST;
}

我是正确的思维,这是安全的吗?

PS,我知道,这将是做同样的事情的一个更好的方法:

  char * const的GetString的()
{
  返回测试;
}

编辑:
道歉,函数签名当然应该是:

 为const char * GetString的();


解决方案

第一个例子:偏于安全

  char * const的GetString的()
{
  静态炭STEST [5];
  的strcpy(STEST,测试);
  返回STEST;
}

虽然不建议,这是安全的,静态变量的范围仍然活着,即使该函数的范围结束。这个功能不是很线程安全的。一个更好的功能会得到你传递一个char *缓冲区和最大尺寸为的GetString()函数来填充。

在这个特定的功能不被视为一个重入函数,因为可重入函数不绝,除其他事项外,将返回地址静态(全局)非常量数据。

有关折返功能的见维基百科。

第二个例子:完全不安全

  char * const的GetString的()
{
  返回测试;
}

如果你没有一个const char这将是安全的*。
你给是不是安全。的原因是因为字符串可以存储在只读存储器段,并允许他们进行修改将导致未定义的结果。

char * const的意思,你不能改变指针所指向的地址。为const char *意味着你不能改变这个指针所指向的元素。

结论:

您应该考虑之一:

1)如果您有机会获得code然后修改的GetString采取一个char *缓冲区的参数,以填补和最大尺寸来使用。

2)如果您没有访问到code,但你必须调用它,在这种由互斥锁保护的另一个函数包装这个方法。新方法是在1描述

I'm working with some code that widely uses the idiom of returning a pointer to a static local variable. eg:

char* const GetString()
{
  static char sTest[5];
  strcpy(sTest, "Test");
  return sTest;
}

Am I right in thinking that this is safe?

PS, I know that this would be a better way of doing the same thing:

char* const GetString()
{
  return "Test";
}

Edit: Apologies, the function signature should of course be:

const char* GetString();

解决方案

First example: Somewhat safe

char* const GetString()
{
  static char sTest[5];
  strcpy(sTest, "Test");
  return sTest;
}

Although not recommended, this is safe, the scope of a static variable remains alive even when the scope of the function ends. This function is not very thread safe at all. A better function would get you to pass a char* buffer and a max size for the GetString() function to fill.

In particular this function is not considered a reentrant function because reentrant functions must not, amongst other things, return the address to static (global) non-constant data.

See wikipedia for reentrant functions.

Second example: Completely unsafe

char* const GetString()
{
  return "Test";
}

This would be safe if you did a const char *. What you gave is not safe. The reason is because string literals can be stored in a read only memory segment and allowing them to be modified will cause undefined results.

char* const means that you can't change the address the pointer is pointing to. const char * means that you can't change the elements that this pointer is pointing to.

Conclusion:

You should consider either:

1) If you have access to the code then modify the GetString to take a parameter of a char* buffer to fill and a max size to use.

2) If you do not have access to the code, but you must call it, wrap this method in another function which is protected by a mutex. The new method is as described in 1.

这篇关于返回一个指向静态局部变量安全吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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