News for hackers. Stuff that matters.
Re:C Strings and my slow descent to madness by habibur on Thursday April 06, 2023 @09:48AM (#35468270)
I don't use null terminated strings. ptr+len struct everywhere. And when I need to call an API, like fopen, I make a temporary copy of that string + the null termination, do my work and then free it.

You can printf non-null terminated strings too. Check printf("%.*s", length, strptr).

Re:C Strings and my slow descent to madness by torstenvl on Thursday April 06, 2023 @10:06AM (#35468480)
> You can printf non-null terminated strings too. Check printf("%.s", length, strptr).*

I haven't checked yet, but I'm about 90% confident that's UB. Is printf() guaranteed not to read to the end of the string when you give it a length?

Re:C Strings and my slow descent to madness by nwellnhof on Thursday April 06, 2023 @10:32AM (#35468792)
Yes, it is. From the C11 spec:

> Characters from the array are written up to (but not including) the terminating null character. If the precision is specified, no more than that many bytes are written. If the precision is not specified or is greater than the size of the array, the array shall contain a null character.

Re:C Strings and my slow descent to madness by torstenvl on Friday April 07, 2023 @09:37AM (#35481431)
Thanks! I guess I didn't realize expressio unius est exclusio alterius applies in the C standard :D
Re:C Strings and my slow descent to madness by habibur on Thursday April 06, 2023 @12:54PM (#35471119)
Won't read a single byte beyond the length you give it.

And this is a standard practice in libraries for printing pre-determined lengthed string.

Re:C Strings and my slow descent to madness by t43562 on Thursday April 06, 2023 @11:27AM (#35469666)
A long time ago my solution was ptr+len but I allocated 1 more byte so that if a string had to be given to libc, I could terminate it at that time. No need for a copy then.
Re:C Strings and my slow descent to madness by wvenable on Thursday April 06, 2023 @12:32PM (#35470795)
BASIC strings in Windows -- you store the length in the 4 bytes before the pointer to the string and put a null terminator at the end.

https://learn.microsoft.com/en-us/previous-versions/windows/...