Non null-terminated string compiler option for gcc

耗尽温柔 提交于 2019-11-29 10:22:41

No need for a compiler option, it's already non-NUL terminated. The standard says a NUL should only be added if it can fit, otherwise it would be an overflow. It may just be that the next byte in memory past your array is \0

§ 6.7.8p14

An array of character type may be initialized by a character string literal, optionally enclosed in braces. Successive characters of the character string literal (including the terminating null character if there is room or if the array is of unknown size) initialize the elements of the array.

No. NUL-terminated strings are intrinsic to the language. You can have a character array though, and set each character one by one:

char hex [] = {'0', '1', '2', ... 'F'};

You answered your own question. If you explicitly give the array a length, as in:

const char hex[16] = "0123456789ABCDEF";

then of course it won't be null-terminated because there is no storage reserved for null termination. (hex[16] is outside the bounds of the object and thus reading or writing it is undefined behavior. If it happens to read as 0, that's UB for ya...)

It's only if you leave the length implicit, as in:

const char hex[] = "0123456789ABCDEF";

or if you use the string literal as an object rather than as an initializer, that it will have null termination.

By the way, why do you care if the null termination is there or not, if you're not planning to use it. Are you trying to shave bytes off your binary? :-)

Strings are null terminated in C. If you want to populate a non-null-terminated char array you can use an array initializer.

I believe the question is a bit unclear: In C, the qoted initialization:

static const char hex[16] = "0123456789ABCDEF";

is legal. In C++, it is not. So it is one of the pieces of code, that fail (fortunately at compile time), when you move from C to C++.

It would be nice to have a way to force string literals without termination \0 byte. Something like:

static const char hex[16] = "0123456789ABCDEF\!0";

where the \!0 at the end tells the compiler to not zero-terminate the string! \! or even \!0 anywhere else in the string would behave unmodified, so just put out a literal ! or !0 .

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!