1

是否值得检查不应失败的方法的返回码?

例如,我通常这样做:

char buf[MAXBUF];
snprintf(buf, sizeof(MAXBUF), "%s.%d", str, time);

即使我知道 MAXBUF 足够大以满足我的目的,检查 snprintf 的返回代码是否是一种好习惯?即使代码变得更加冗长,这样做似乎也很有意义。

4

5 回答 5

4

Short Answer: Yes

Long Answer: Yes because it catches silly mistakes like the below.

char buf[MAXBUF];
snprintf(buf, sizeof(MAXBUF), "%s.%d", str, time);

// sizeof(MAXBUF) is probably equal to sizeof(int)

The main problem with C code is that people don't actually check the return codes (because they thought the code could never fail). So the moral of the story is don't assume and check. It does not actually add much to the code. You should probably exit/abort if things that should not go wrong actually go wrong and then you will find them early in the testing cycle.

C++ solution:

std::stringstream  buf;
buf << str << "." << time;  // No chance of error as compiler does the work.
于 2010-11-02T18:08:21.880 回答
2

这取决于。将来,MAXBUF格式字符串或输入值是否可能会发生变化?如果调用失败,您的代码可以采取哪些现实的行动方案?答案完全取决于您的应用程序。

一种可能性是简单地assert返回值符合预期,而不是默默地失败。这不会在生产构建中花费您任何成本,并且不会增加源代码的冗长性。

于 2010-11-02T17:54:58.743 回答
0

You are weighing the onetime cost of a simple error check when the code is written, versus the repeated cost of deciding whether or not to check it depending on context, and if not, possible production bugs due to misunderstood assumptions or later maintenance by other people.

That's a no brainer in most cases.

于 2010-11-02T18:06:27.903 回答
0

If the buffer ever is somehow too small, then the string will be truncated. You'd hope that your tests will catch this, since you will produce incorrect results.

Then again, checking the return value needn't add much verbosity. As Oli says, assert is cheap:

int result = snprintf(buf, sizeof buf, "%s.%d", str, time);
assert(result >= 0 && result <= (sizeof buf) - 1);

To be honest I wouldn't always check, but it depends why I think str can't be that long. If it's for a really fundamental reason (like it's a filename from a dirent structure, and MAXBUF is defined in terms of MAX_FILENAME), then I probably wouldn't bother. If it's because there's some check elsewhere, or it's the caller's responsibility to pass in a string only of a certain length, then it might be an idea to assert, just on the off-chance of catching someone else's bug some day. Obviously if str is any kind of unchecked external input then it's essential to test.

于 2010-11-02T18:07:00.127 回答
0

这可能是最好的,以防万一,但如果您确定永远不会超过 MAXBUF 的大小,那么它只会增加几个时钟周期。

于 2010-11-02T17:55:03.157 回答