Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

utf8 strings and malloc in c

With "opendir" and "readdir" i do read a directories content. During that process i do some strings manipulation / allocation: something like that:

int stringlength = strlen(cur_dir)+strlen(ep->d_name)+2;
char *file_with_path = xmalloc(stringlength); //xmalloc is a malloc wrapper with some tests (like no more memory)
snprintf (file_with_path, (size_t)stringlength, "%s/%s", cur_dir, ep->d_name);

But what if a string contains a two-byte utf8 char? How do you handle that issue?

stringlength*2?

Thanks

like image 836
Jonas Schnelli Avatar asked Sep 09 '26 11:09

Jonas Schnelli


1 Answers

strlen() counts the bytes in the string, it doesn't care if the contained bytes represent UTF-8 encoded Unicode characters. So, for example, strlen() of a string containing an UTF-8 encoding of "aöü" would return 5, since the string is encoded as "a\xc3\xb6\xc3\xbc".

like image 85
sth Avatar answered Sep 11 '26 00:09

sth



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!