*以双'\0'结尾的字符

*char ending with double '\0'

由于某些字符串末尾缺少字符“\0”,我的代码崩溃了。

我很清楚为什么我们必须使用这个终止字符。我的问题是, 将潜在的第二个空字符添加到字符数组是否有问题 - 以解决字符串问题?

我认为向每个字符串添加一个'\0'比验证它是否需要然后添加它更便宜,但我不知道这样做是否好。

拥有 '[=10=]' 不是问题,除非您没有超出该字符数组的范围。

你必须明白,'[=10=]' 两次意味着任何字符串操作都不知道还有第二个 '[=10=]'。他们只会读到第一个 '[=10=]',然后就读完了。对于他们来说,第一个 '[=10=]' 是 Null 终止字符,之后不应该有任何内容。

I think it's cheaper just add a '[=14=]' to every string than verify if it needs and then add it, but I don't know if it's a good thing to do.

你会在哪里添加它?假设我们做了这样的事情:

char *p = malloc(32);

现在,如果我们知道分配的长度,我们可以将 '[=11=]' 作为分配区域的最后一个字符,如 p[31] = '[=12=]'。但是我们不知道字符串的内容应该有多长。如果应该只有 foobar,那么仍然会有 25 个字节的垃圾,如果处理或打印可能会导致其他问题。

更不用说如果你只有指向字符串的指针,就很难知道分配区域的长度。

修复构建字符串的位置可能会更好。

is there a problem to have this char ('[=12=]') twice at the end of a string?

这个问题不够明确,因为 "string" 对人们意味着不同的东西。
让我们使用 C 规范定义,因为这是一个 C post.

A string is a contiguous sequence of characters terminated by and including the first null character. C11 §7.1.1 1

因此,字符串 不能有 2 个 空字符 ,因为字符串在到达第一个字符时结束。

相反,重新解析为 "is there a problem adding a potential 2nd null character to a character array - to solve string problems?"


尝试向字符串添加空字符的问题是混淆。 str...() 函数使用上面定义的 C 字符串。

// If str1 was not a string, strcpy(str1, anything) would be undefined behavior.
strcpy(str1, "[=10=]");  // no change to str1

char str2[] = "abc";
str2[strlen(str2)] = '[=10=]'; // OK but only, re-assigns the [=10=] to a [=10=]
// attempt to add another [=10=]
str2[strlen(str2)+1] = '[=10=]'; // Bad: assigning outside `str2[]` as the array is too small

char str3[10] = "abc";
str3[strlen(str3)+1] = '[=10=]'; // OK, in this case
puts(str3);                  // Adding that [=10=] served no purpose

正如许多人评论的那样,添加备用 '[=12=]' 并不能直接解决代码的根本问题。

未经post编辑的代码才是真正需要解决的问题,而不是尝试附加第二个'[=12=]'