English 中文(简体)
AL(ALWAYS)是否终止?
原标题:Is snprintf() ALWAYS null terminating?
  • 时间:2011-10-09 22:18:54
  •  标签:
  • c
  • posix
  • libc

print是否总是否认目的地缓冲?

换言之,这足以:

char dst[10];

snprintf(dst, sizeof (dst), "blah %s", somestr);

或者,如果某些方面已经足够长,你必须这样做吗?

char dst[10];

somestr[sizeof (dst) - 1] =   ;
snprintf(dst, sizeof (dst) - 1, "blah %s", somestr);

我对标准所说的话和某些民众的平衡可能做的不是标准行为都感兴趣。

最佳回答

As the other answers establish: It should:

snprintf ... Writes the results to a character string buffer. (...) will be terminated with a null character, unless buf_size is zero.

So all you have to take care is that you don t pass an zero-size buffer to it, because (obviously) it cannot write a zero to "nowhere".


但是,beware , 微软的图书馆没有<>> > 功能称为snprintf,但改为, 历史上有以下功能:_snprintf http://www.em>does not append a terminating no. The docs (VS 2012 ~~ VS2013):

http://msdn.microsoft.com/en-us/library/2ts7cx93%28v=vs.110%29.aspx

Return Value

Let len be the length of the formatted data string (not including the terminating null). len and count are in bytes for _snprintf, wide characters for _snwprintf.

  • If len < count, then len characters are stored in buffer, a null-terminator is appended, and len is returned.

  • If len = count, then len characters are stored in buffer, no null-terminator is appended, and len is returned.

  • If len > count, then count characters are stored in buffer, no null-terminator is appended, and a negative value is returned.

(...)

视觉演播室2015年<<<>a>(VC14)显然介绍了符合snprintf的功能,但与主要强调和non的遗产。 仍然存在着终止行为:

The snprintf function truncates the output when len is greater than or equal to count, by placing a null-terminator at buffer[count-1]. (...)

For all functions other than snprintf, if len = count, len characters are stored in buffer, no null-terminator is appended, (...)

问题回答

printf(3) 单页。

<代码>snprintf()和vsnprintf()在大多数<代码>上写成<>size bytes (包括拆散的拖车())至str

因此,如果大小和幅度大于1,则无需终止。

根据C标准,除非缓冲尺寸为0,vsnprintf( rel=“nofollow noretinger”>

snprintf() function shall beequi to sprintf(),并加上一则论点,其中说明S.提到的缓冲地带的规模。 如果是零,则任何东西都不得写,并且可能是一纸空文。 否则,除第1类外的tes产品不应被丢弃,而不应被写到阵列上,而任何 by都是在实际写入阵列的tes末书写的。

因此,如果你需要知道如何分配一个大的缓冲地带,使用一个零的大小,那么你就可以把一个无效点作为目的地。 请注意,我与SPOSIX网页有关,但这些网页明确表示,标准C和PPOSIX之间并无任何差别,因为它们涉及同一理由:

该参考网页上描述的功能与ISOC标准一致。 此处所述要求与ISOC标准之间的任何冲突都是无意的。 该编号为POSIX.1-2008,服从ISOC标准。

Be wary of thesoft edition of vsnprintf(。 当缓冲区没有足够的空间时(标准功能返回时,标准功能恢复所需时间为1)。 不完全清楚的是,微软版本在错误条件下终止其产出,而标准C版本则这样做。

但是,注意到微软已经修改了规则(),因为这一答复最初是书面的:

Beginning with the UCRT in Visual Studio 2015 and Windows 10, vsnprintf is no longer identical to _vsnprintf. The vsnprintf function conforms to the C99 standard; _vnsprintf is kept for backward compatibility with older Visual Studio code.

类似评论适用于<代码>snprintf()和sprintf()

Note also the answers to Do you use the TR 24731 safe functions? (see MSDN for the Microsoft version of the vsprintf_s()) and the Mac solution for the safe alternatives to unsafe C standard library functions?

Some older versions of SunOS did weird things with snprintf and might have not NUL-terminated the output and had return values that didn t match what everyone else was doing, but anything that has been released in the past 10 years have been doing what C99 says.

模糊性源自《标准》本身。 C99和C11对<代码>snprintf功能的描述相同。 C99的描述如下:

7.19.6.5 The snprintf function
Synopsis
1 #include <stdio.h> int snprintf(char * restrict s, size_t n, const char * restrict format, ...);
Description
2 The snprintf function is equivalent to fprintf, except that the output is written into an array (specified by argument s) rather than to a stream. If n is zero, nothing is written, and s may be a null pointer. Otherwise, output characters beyond the n-1st are discarded rather than being written to the array, and a null character is written at the end of the characters actually written into the array. If copying takes place between objects that overlap, the behavior is undefined.
Returns
3 The snprintf function returns the number of characters that would have been written had n been sufficiently large, not counting the terminating null character, or a negative value if an encoding error occurred. 因此,如果而且只有在被退回的价值不否定,且低于<条码>n时,被完全删除的产出才算出。.

www.un.org/Depts/DGACM/index_spanish.htm 一方面, 第一句

否则,<>t>n-1<>>t/code> 以外的<>strong> 信号特性被弃置,而不是写给阵列,,在实际写成的特性末尾写成无效。

says that
if (the s points to a 3-character-long array, and) n is 3, then 2 characters will be written, and the characters beyond the 2nd one are discarded; then the null character is written after those 2 (and the null character will be the 3rd character written).

And this I believe answers the original question.
THE ANSWER:
If copying takes place between objects that overlap, the behavior is undefined.
If n is 0 then nothing is written to the output
otherwise, if no encoding errors encountered, the output is ALWAYS null-terminated (regardless of whether the output fits in the output array or not; if not then some characters are discarded such that the output array is never overflown),
otherwise (if encoding errors are encountered) the output can stay non-null-terminated.

On the other hand
The last sentence

因此,如果而且只有在被退回的价值不否定,且低于<条码>n时,被完全删除的产出才算出。

gives ambiguity (or my English is not good enough). I can interpret this sentence in at least two ways:
1. The output is null-terminated if and only if the returned value is nonnegative and less than n (which means that if the returned value is not less than n, i.e. the output (including the terminating null character) does not fit in the array, then the output is not null-terminated).
2. The output is complete (no characters have been discarded) if and only if the returned value is nonnegative and less than n.


I believe that the interpretation 1 above contradicts THE ANSWER, causes misunderstanding and lengthy discussions. That is why the last sentence describing the snprintf function needs a change in order to remove any ambiguity (which gives grounds for writing a Proposal to the C language Standard).
The example of non-ambiguous wording I believe can be taken from http://en.cppreference.com/w/c/io/fprintf (see 4)), thanks to @"Martin Ba" for the link.

另见“





相关问题
Fastest method for running a binary search on a file in C?

For example, let s say I want to find a particular word or number in a file. The contents are in sorted order (obviously). Since I want to run a binary search on the file, it seems like a real waste ...

Print possible strings created from a Number

Given a 10 digit Telephone Number, we have to print all possible strings created from that. The mapping of the numbers is the one as exactly on a phone s keypad. i.e. for 1,0-> No Letter for 2->...

Tips for debugging a made-for-linux application on windows?

I m trying to find the source of a bug I have found in an open-source application. I have managed to get a build up and running on my Windows machine, but I m having trouble finding the spot in the ...

Trying to split by two delimiters and it doesn t work - C

I wrote below code to readin line by line from stdin ex. city=Boston;city=New York;city=Chicago and then split each line by ; delimiter and print each record. Then in yet another loop I try to ...

Good, free, easy-to-use C graphics libraries? [closed]

I was wondering if there were any good free graphics libraries for C that are easy to use? It s for plotting 2d and 3d graphs and then saving to a file. It s on a Linux system and there s no gnuplot ...

Encoding, decoding an integer to a char array

Please note that this is not homework and i did search before starting this new thread. I got Store an int in a char array? I was looking for an answer but didn t get any satisfactory answer in the ...

热门标签