· 2 min read

String Handling in C

This article was auto-translated from Chinese. Some nuances may be lost in translation.

In C, you can obtain the length of a string using strlen. However, each call to strlen takes O(n)O(n) time. For applications that perform frequent string operations, this can easily become a performance bottleneck when strings are long—especially in high-traffic applications. One solution is to track the string length in a separate variable and update it whenever the string is modified. That way, retrieving the string length only requires reading this variable, bringing the time complexity down to O(1)O(1).

Another thing to watch out for is that C makes no assumptions about your buffer size. You need to be very careful when performing operations like concatenation. For example, if you write:

#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 concatenates the contents of buf2 onto 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;
}

Running this will result in an error. This happens because concatenating buf1 and buf2 exceeds a size of 4, leading to a buffer overflow. The solution is to check beforehand whether the combined string length will cause an overflow before performing the concat operation, and reallocate memory if it will.

Related Posts

Explore Other Topics