确保功能参数的静态存储 [英] Ensure static storage for a function parameter

查看:31
本文介绍了确保功能参数的静态存储的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们有这个函数原型:

  BNode *b_new_node(const char *name, int pos, int len, const char *val);

使用此代码(和类似代码)的大多数代码都是自动生成的代码,如下所示:

Most of the code using this(and similar) are autogenerated code, and looks like:

 b = b_new_node("foo.bar.id.1", 0, 10, some_data);

该函数分配一个新的BNode并将 val 字符串复制到其中,但是它只是将 name 成员分配给一个指针,例如

The function allocates a new BNode and copies the val string into it, but it just assigns the name member to a pointer, e.g.

 b_strlcpy(new_node->val, val, sizeof new_node->val);
 new_node->name = name;

如果b_new_node("foo.bar.id.1",0,10,some_data)中的第一个参数,这将造成严重破坏不是字符串文字,或者不是具有静态存储期限的内容,例如堆栈上的缓冲区.

This wrecks havoc if the first argument in b_new_node("foo.bar.id.1", 0, 10, some_data); is not a string literal, or otherwise something with static storage duration, but e.g. a buffer on the stack.

无论如何,是否有gcc(其他编译器也很受关注),我们可以进行编译时检查以确保传入的此参数是静态存储的?

Is there anyway, with gcc (other compilers are of interest too), we can have a compile time check that this argument is passed in is of static storage ?

(当然,避免这些可能出现的问题的最简单方法是将参数也复制到节点中-我们使用该方法进行的测量将内存需求提高了50%,并使程序运行速度降低了10%,因此该方法是不可取的.)

(ofcourse the easy way to avoid these possible problems is to copy that argument too into the node - the measurements we did with that approach rises the memory need by 50% and slows the program down by 10%, so that approach is undesirable).

推荐答案

通常没有;没有C提供的工具可以知道指针是否指向静态存储中的某物.特定的环境和数据结构可能会改变环境-例如检查指向的地址是否在只读内存段.

Generally no; there is no C-provided facility to know whether or not a pointer points to something in static storage. Specific environments and data structures may change the circumstances - such as checking if the pointed-to address is in a read-only memory segment.

要消除重复的值(如 name 所指出的那样),可以使用 the轻量级模式,它与字符串实习没有太大区别.

To eliminate duplicated values, as pointed to by name, you could use the flyweight pattern which is not very different from string interning.

基本上,您将构建一组遇到的令牌的中央集,并仅存储对每个令牌的引用.引用可以是数组索引或指针.

Basically you build a central set of encountered tokens and store only the reference to each token. The references could be array indices or pointers.

为了能够快速清理,您可以将flyweight模式与引用计数结合使用计数为零表示没有引用.

To be able to clean-up quickly, you could combine the flyweight pattern with reference counting where a count of zero, means no references left.

要保持中央存储的高性能,请使用快速查找的数据结构(例如集合),或者使用如果使用引用计数,则="nofollow">地图.

To keep performance of the central store high, use a data structure where look-up is fast such as a set, or with a map if reference counting is used.

这篇关于确保功能参数的静态存储的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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