用C字符串处理方法 [英] String-handling practices in C

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

问题描述

我开始在这是要与文字工作主要平原C(C99)的新项目。由于外部项目的限制,这code的是非常简单和紧凑,不构成除了libc和类似无处不系统库外部依赖或库的单一源 - code文件的。

I'm starting a new project in plain C (c99) that is going to work primarily with text. Because of external project constraints, this code has to be extremely simple and compact, consisting of a single source-code file without external dependencies or libraries except for libc and similar ubiquitous system libraries.

根据这一理解,什么是一些最佳做法,陷阱,技巧或其他技术,可以帮助使项目的字符串处理更加强大和安全吗?

With that understanding, what are some best-practices, gotchas, tricks, or other techniques that can help make the string handling of the project more robust and secure?

推荐答案

如果没有关于你code是干什么的,我会建议在设计这样所有的接口的任何附加信息:

Without any additional information about what your code is doing, I would recommend designing all your interfaces like this:

size_t foobar(char *dest, size_t buf_size, /* operands here */)

像语义的snprintf


  • DEST 点,大小至少 buf_size 的缓冲区。

  • 如果 buf_size 为零,空/无效指针是 DEST 并没有什么将被写入接受。

  • 如果 buf_size 不为零, DEST 始终空值终止。

  • 每个功能 foobar的返回完整的非截断输出的长度;输出已截断,如果 buf_size 小于或等于返回值。

  • dest points to a buffer of size at least buf_size.
  • If buf_size is zero, null/invalid pointers are acceptable for dest and nothing will be written.
  • If buf_size is non-zero, dest is always null-terminated.
  • Each function foobar returns the length of the full non-truncated output; the output has been truncated if buf_size is less than or equal to the return value.

此方式,当主叫方可以容易知道的需要的,可预先得到一个足够大的缓冲目的地缓冲区大小。如果主叫不能很容易地知道,它可以与任何一个为零的参数为 buf_size ,或用缓冲这可能足够大,如果你只跑了重试一次调用该函数空间不足。

This way, when the caller can easily know the destination buffer size that's required, a sufficiently large buffer can be obtained in advance. If the caller cannot easily know, it can call the function once with either a zero argument for buf_size, or with a buffer that's "probably big enough" and only retry if you ran out of space.

您也可以做出这样的呼吁类似于GNU asprintf 函数的包装版本,但是如果你希望你的code尽可能我会灵活避免在实际的字符串函数做任何分配。处理失败的可能性是在呼叫者水平总是容易,并且许多呼叫者可以确保失败是从未使用本地缓冲或在该方案获得更早缓冲剂的可能性,使得较大的操作的成功或失败是原子(这大大简化了错误处理)。

You can also make a wrapped version of such calls analogous to the GNU asprintf function, but if you want your code to be as flexible as possible I would avoid doing any allocation in the actual string functions. Handling the possibility of failure is always easier at the caller level, and many callers can ensure that failure is never a possibility by using a local buffer or a buffer that was obtained much earlier in the program so that the success or failure of a larger operation is atomic (which greatly simplifies error handling).

这篇关于用C字符串处理方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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