String Handling in C
In C, you can obtain the length of a string using strlen. However, each call to strlen takes 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 .
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
- When a Measure Becomes a Target: From the Window Tax to Pull Request Counts I once wrote a script to tally how many PRs I contributed in a quarter, how many reviews I left, and how many tickets I closed, hoping to use numbers to prove my output to my manager. My manager simply remarked that performance isn't just about output. Years later, I finally understood—when a measure becomes a target, it ceases to be a good measure. From the British window tax and the Hanoi rat bounty to evaluating developers by PR counts today, the underlying mechanism is exactly the same.
- Using Cloudflare Images for Image Storage and Transformation Putting an image on a webpage is the simplest task in frontend development. But doing it properly—including resizing, generating multiple formats, and withstanding heavy traffic—is actually an entire end-to-end solution. Eventually, I offloaded everything to Cloudflare Images, keeping only a single original image.
- Stop Using AWS Access Keys Access Keys are an easily overlooked security risk in AWS. By pairing OIDC with IAM Roles, GitHub Actions can securely operate AWS resources without storing any secrets.
- Database Primary Keys: AUTO_INCREMENT, UUID, and UUIDv7 Backend developers often face the choice of primary keys: should you use auto-increment or UUID? What about collisions? How does UUIDv7 compare to created_at + index in performance? Here are the design decisions and benchmark results from testing 20 million rows.