Kalan's Blog

Software Engineer / Taiwanese / Life in Fukuoka

Current Theme light

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

作者

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

愷開 | Kalan

Hi, I'm Kai. I'm Taiwanese and moved to Japan in 2019 for work. Currently settled in Fukuoka. In addition to being familiar with frontend development, I also have experience in IoT, app development, backend, and electronics. Recently, I started playing electric guitar! Feel free to contact me via email for consultations or collaborations or music! I hope to connect with more people through this blog.