返回指向静态局部变量的指针是否安全? [英] Is returning a pointer to a static local variable safe?

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

问题描述

我正在处理一些广泛使用返回指向静态局部变量的指针的习惯用法的代码.例如:

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,我知道这会是做同样事情的更好方法:

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

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

抱歉,函数签名当然应该是:

Apologies, the function signature should of course be:

const char* GetString();

推荐答案

第一个例子:有点安全

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

虽然不推荐,但这是安全的,即使函数的作用域结束,静态变量的作用域仍然有效.这个函数根本不是线程安全的.一个更好的函数会让你传递一个 char* 缓冲区 和一个 maxsize 以便 GetString() 函数来填充.

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 maxsize 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 reentrant functions.

第二个例子:完全不安全

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

如果您使用 const char *,这将是安全的.你给的东西不安全.原因是因为字符串文字可以存储在只读内存段中,并且允许修改它们会导致未定义的结果.

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 (const 指针) 意味着你不能改变指针指向的地址.const char *(指向const的指针)意味着你不能改变这个指针所指向的元素.

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

结论:

您应该考虑:

1) 如果您有权访问代码,则修改 GetString 以获取要填充的 char* 缓冲区 的参数和 maxsize> 使用.

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

2) 如果您无权访问代码,但必须调用它,请将此方法包装在另一个受互斥锁保护的函数中.新方法如1所述.

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天全站免登陆