Kalan's Blog

Kalan 頭像照片,在淡水拍攝,淺藍背景

四零二曜日電子報上線啦!訂閱訂起來

Software Engineer / Taiwanese / Life in Fukuoka
This blog supports RSS feed (all content), you can click RSS icon or setup through third-party service. If there are special styles such as code syntax in the technical article, it is still recommended to browse to the original website for the best experience.

Current Theme light

我會把一些不成文的筆記或是最近的生活雜感放在短筆記,如果有興趣的話可以來看看唷!

Please notice that currenly most of posts are translated by AI automatically and might contain lots of confusion. I'll gradually translate the post ASAP

String Processing in the C Language

In the C language, you can use strlen to obtain the length of a string. However, each call to strlen has a time complexity of O(n)O(n). For applications that frequently access string operations, this can result in performance bottlenecks, especially in high-traffic applications. One solution is to save the string length in another variable and update it whenever there are string operations. This way, accessing the string length only requires accessing this variable, with a time complexity of O(1)O(1).

Another thing to note is that C language does not have any default buffer length. So, you need to be careful when performing operations like concatenation. For example, if you use strcat:

#include <stdio.h>
#include <string.h>

int main(void) {
  char buf1[20] = "abc";
  char buf2[] = "def";
  strcat(buf1, buf2);
  printf("%s\n", buf1);
  return 0;
}

This code will combine the contents of buf2 with buf1 and append it to the end of buf1. However, if we reduce the size of buf1 to 5:

#include <stdio.h>
#include <string.h>

int main(void) {
+ char buf1[4] = "abc";
  char buf2[] = "def";
  strcat(buf1, buf2);

  printf("%s\n", buf1);
  return 0;
}

After execution, you will notice that the code has an error. This is because the concatenation of buf1 and buf2 exceeds the size of 4, resulting in a buffer overflow. The solution is to check the length of the combined string before performing the concatenation operation. If it will cause an overflow, you need to reallocate memory accordingly.

Prev

Exploring the form and data retrieval mechanism of remix

Next

Rewrite the entire blog using Next.js

If you found this article helpful, please consider buy me a drink ☕️ It'll make my ordinary day shine✨

Buy me a coffee